import React = require('react');
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, observable } from 'mobx';
import { observer } from 'mobx-react';
import ReactLoading from 'react-loading';
import Typist from 'react-typist';
import { Doc } from '../../../../fields/Doc';
import { DocUtils, Docs } from '../../../documents/Documents';
import './GPTPopup.scss';
import { Button, IconButton } from 'browndash-components';
import { StrCast } from '../../../../fields/Types';

export enum GPTPopupMode {
    SUMMARY,
    EDIT,
}

interface GPTPopupProps {}

@observer
export class GPTPopup extends React.Component<GPTPopupProps> {
    static Instance: GPTPopup;

    @observable
    public visible: boolean = false;
    @action
    public setVisible = (vis: boolean) => {
        this.visible = vis;
    };
    @observable
    public loading: boolean = false;
    @action
    public setLoading = (loading: boolean) => {
        this.loading = loading;
    };
    @observable
    public text: string = '';
    @action
    public setText = (text: string) => {
        this.text = text;
    };
    @observable
    public mode: GPTPopupMode = GPTPopupMode.SUMMARY;
    @action
    public setMode = (mode: GPTPopupMode) => {
        this.mode = mode;
    };

    @observable
    public highlightRange: number[] = [];
    @action callSummaryApi = () => {};
    @action callEditApi = () => {};
    @action replaceText = (replacement: string) => {};

    @observable
    private done: boolean = false;
    @action
    public setDone = (done: boolean) => {
        this.done = done;
    };
    @observable
    private sidebarId: string = '';
    @action
    public setSidebarId = (id: string) => {
        this.sidebarId = id;
    };

    // reference
    // if (focusNode) {
    //     const anchor = srcWeb?.ComponentView?.getAnchor?.(true);
    //     anchor && DocUtils.MakeLink(htmlDoc, anchor, {});
    // }
    @observable
    private pdfAnchor: Doc | undefined;
    @action
    public setPdfAnchor = (anchor: Doc) => {
        this.pdfAnchor = anchor;
    };

    public addDoc: (doc: Doc | Doc[], sidebarKey?: string | undefined) => boolean = () => false;

    /**
     * Transfers the summarization text to a sidebar annotation text document.
     */
    private transferToText = () => {
        const newDoc = Docs.Create.TextDocument(this.text.trim(), {
            _width: 200,
            _height: 50,
            _layout_fitWidth: true,
            _layout_autoHeight: true,
        });
        this.addDoc(newDoc, this.sidebarId);
        if (this.pdfAnchor) {
            DocUtils.MakeLink(newDoc, this.pdfAnchor, {
                link_relationship: 'GPT Summary',
            });
        }
    };

    constructor(props: GPTPopupProps) {
        super(props);
        GPTPopup.Instance = this;
    }

    componentDidUpdate = () => {
        if (this.loading) {
            this.setDone(false);
        }
    };

    summaryBox = () => (
        <>
            <div>
                {this.heading('SUMMARY')}
                <div className="content-wrapper">
                    {!this.loading &&
                        (!this.done ? (
                            <Typist
                                key={this.text}
                                avgTypingDelay={15}
                                cursor={{ hideWhenDone: true }}
                                onTypingDone={() => {
                                    setTimeout(() => {
                                        this.setDone(true);
                                    }, 500);
                                }}>
                                {this.text}
                            </Typist>
                        ) : (
                            this.text
                        ))}
                </div>
            </div>
            {!this.loading && (
                <div className="btns-wrapper">
                    {this.done ? (
                        <>
                            {/* <button className="icon-btn" onClick={this.callSummaryApi}>
                                <FontAwesomeIcon icon="redo-alt" size="lg" />
                            </button>
                            <button
                                className="text-btn"
                                onClick={e => {
                                    this.transferToText();
                                }}>
                                Transfer to Text
                            </button> */}
                            <IconButton onClick={this.callSummaryApi} icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} color={StrCast(Doc.UserDoc().userVariantColor)} />
                            <Button text="Transfer To Text" onClick={this.transferToText} color={StrCast(Doc.UserDoc().userVariantColor)} />
                        </>
                    ) : (
                        <div className="summarizing">
                            <span>Summarizing</span>
                            <ReactLoading type="bubbles" color="#bcbcbc" width={20} height={20} />
                            <button
                                className="btn-secondary"
                                onClick={e => {
                                    this.setDone(true);
                                }}>
                                Stop Animation
                            </button>
                        </div>
                    )}
                </div>
            )}
        </>
    );

    editBox = () => {
        const hr = this.highlightRange;
        return (
            <>
                <div>
                    {this.heading('TEXT EDIT SUGGESTIONS')}
                    <div className="content-wrapper">
                        {hr && (
                            <div>
                                {this.text.slice(0, hr[0])} <span className="highlighted-text">{this.text.slice(hr[0], hr[1])}</span> {this.text.slice(hr[1])}
                            </div>
                        )}
                    </div>
                </div>
                {hr && !this.loading && (
                    <>
                        <div className="btns-wrapper">
                            <>
                                <button className="icon-btn" onPointerDown={this.callEditApi}>
                                    <FontAwesomeIcon icon="redo-alt" size="lg" />
                                </button>
                                <button
                                    className="text-btn"
                                    onClick={e => {
                                        this.replaceText(this.text);
                                    }}>
                                    Replace Text
                                </button>
                            </>
                        </div>
                        {this.aiWarning()}
                    </>
                )}
            </>
        );
    };

    aiWarning = () =>
        this.done ? (
            <div className="ai-warning">
                <FontAwesomeIcon icon="exclamation-circle" size="sm" style={{ paddingRight: '5px' }} />
                AI generated responses can contain inaccurate or misleading content.
            </div>
        ) : (
            <></>
        );

    heading = (headingText: string) => (
        <div className="summary-heading">
            <label className="summary-text">{headingText}</label>
            {this.loading && <ReactLoading type="spin" color="#bcbcbc" width={14} height={14} />}
        </div>
    );

    render() {
        return (
            <div className="summary-box" style={{ display: this.visible ? 'flex' : 'none' }}>
                {this.mode === GPTPopupMode.SUMMARY ? this.summaryBox() : this.editBox()}
            </div>
        );
    }
}
