import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { SettingsManager } from '../../../util/SettingsManager';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { Button, IconButton } from 'browndash-components';
import ReactLoading from 'react-loading';
import { AiOutlineSend } from 'react-icons/ai';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
import './ImageLabelHandler.scss';
import { gptAPICall, GPTCallType } from '../../../apis/gpt/GPT';
import { InkData } from '../../../../fields/InkField';

@observer
export class SmartDrawHandler extends ObservableReactComponent<{}> {
    static Instance: SmartDrawHandler;

    @observable private _display: boolean = false;
    @observable private _pageX: number = 0;
    @observable private _pageY: number = 0;
    @observable private _yRelativeToTop: boolean = true;
    @observable private _isLoading: boolean = false;
    @observable private _userInput: string = '';
    // @observable public strokes: InkData[] = [];
    private _addToDocFunc: (strokeList: InkData[]) => void = () => {};

    constructor(props: any) {
        super(props);
        makeObservable(this);
        SmartDrawHandler.Instance = this;
    }

    @action
    setIsLoading = (isLoading: boolean) => {
        this._isLoading = isLoading;
    };

    @action
    setUserInput = (input: string) => {
        this._userInput = input;
    };

    @action
    displaySmartDrawHandler = (x: number, y: number, addToDoc: (strokeList: InkData[]) => void) => {
        this._pageX = x;
        this._pageY = y;
        this._display = true;
        this._addToDocFunc = addToDoc;
    };

    @action
    hideLabelhandler = () => {
        this._display = false;
    };

    @action
    waitForCoords = async () => {};

    @action
    drawWithGPT = async (startPoint: { X: number; Y: number }, input: string) => {
        console.log('start point is', startPoint);
        this.setIsLoading(true);
        try {
            const res = await gptAPICall(input, GPTCallType.DRAW);
            if (!res) {
                console.error('GPT call failed');
                return;
            }
            console.log('GPT response:', res);
                // const controlPts: [number, number][][] = JSON.parse(res) as [number, number][][];
                // console.log("Control Points", controlPts);
                // const transformedPts: { X: number; Y: number }[][] = [];
                // controlPts.forEach(stroke => {
                //     stroke.map(pt => {
                //         pt.X += startPoint.X, pt.Y += startPoint.Y;
                //     });
                //     transformedPts.push(stroke);
                // });
            const simplifiedRes: string = res.replace(/[^\d\[\],]/g, '');
            console.log(simplifiedRes)
            try {
                const controlPts: { X: number; Y: number }[][] = JSON.parse(simplifiedRes).map((stroke: [number, number][]) => stroke.map(([X, Y]) => ({ X: X + startPoint.X, Y: Y + startPoint.Y })));
                console.log('transformed points', controlPts);

                // this.strokes = controlPts;
                this._addToDocFunc(controlPts);
            } catch (err) {
                console.error('Incompatible GPT output type');
            }
        } catch (err) {
            console.error('GPT call failed', err);
        }

        this.setIsLoading(false);
        this.setUserInput('');
    };

    render() {
        if (this._display) {
            return (
                <div
                    id="label-handler"
                    className="contextMenu-cont"
                    style={{
                        display: this._display ? '' : 'none',
                        left: this._pageX,
                        ...(this._yRelativeToTop ? { top: Math.max(0, this._pageY) } : { bottom: this._pageY }),
                        background: SettingsManager.userBackgroundColor,
                        color: SettingsManager.userColor,
                    }}>
                    <div>
                        <IconButton tooltip={'Cancel'} onPointerDown={this.hideLabelhandler} icon={<FontAwesomeIcon icon="xmark" />} color={MarqueeOptionsMenu.Instance.userColor} style={{ width: '19px' }} />
                        <input
                            aria-label="label-input"
                            id="new-label"
                            type="text"
                            style={{ color: 'black' }}
                            value={this._userInput}
                            onChange={e => {
                                this.setUserInput(e.target.value);
                            }}
                            placeholder="Enter item to draw"
                        />
                        <Button
                            style={{ alignSelf: 'flex-end' }}
                            text="Send"
                            icon={this._isLoading ? <ReactLoading type="spin" color="#ffffff" width={20} height={20} /> : <AiOutlineSend />}
                            iconPlacement="right"
                            color={MarqueeOptionsMenu.Instance.userColor}
                            onClick={e => {
                                this.drawWithGPT({ X: e.clientX, Y: e.clientY }, this._userInput);
                            }}
                        />
                        {/* <IconButton
                            tooltip={'Generate Drawing'}
                            onPointerDown={() => {
                                const input = document.getElementById('new-label') as HTMLInputElement;
                                const newLabel = input.value;
                                // this.addLabel(newLabel);
                                // this._currentLabel = '';
                                input.value = '';
                            }}
                            icon={<FontAwesomeIcon icon="plus" />}
                            color={MarqueeOptionsMenu.Instance.userColor}
                            style={{ width: '19px' }}
                        />
                        <IconButton tooltip={'Group Images'} icon={<FontAwesomeIcon icon="object-group" />} color={MarqueeOptionsMenu.Instance.userColor} style={{ width: '19px' }} /> */}
                    </div>
                    <div>
                        {/* {this._labelGroups.map(group => {
                            return (
                                <div>
                                    <p>{group}</p>
                                    <IconButton
                                        tooltip={'Remove Label'}
                                        onPointerDown={() => {
                                            this.removeLabel(group);
                                        }}
                                        icon={'x'}
                                        color={MarqueeOptionsMenu.Instance.userColor}
                                        style={{ width: '19px' }}
                                    />
                                </div>
                            );
                        })} */}
                    </div>
                </div>
            );
        } else {
            return <></>;
        }
    }
}
