import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { action, observable, reaction, runInAction } from "mobx";
import React from "react";
import { returnFalse, returnEmptyFilter, returnTrue } from "../../../../../../ClientUtils";
import { emptyFunction } from "../../../../../../Utils";
import { Doc, returnEmptyDoclist } from "../../../../../../fields/Doc";
import { DefaultStyleProvider } from "../../../../StyleProvider";
import { DocumentView, DocumentViewInternal } from "../../../DocumentView";
import { DocCreatorMenu } from "../DocCreatorMenu";
import { TemplatePreviewGrid } from "./TemplatePreviewGrid";
import { observer } from "mobx-react";
import { Transform } from "../../../../../util/Transform";
import { Template } from "../Template";
import { TemplateMenuAIUtils } from "../Backend/TemplateMenuAIUtils";
import { ObservableReactComponent } from "../../../../ObservableReactComponent";
import { IDisposer } from "mobx-utils";
import { ImageField } from "../../../../../../fields/URLField";
import { TemplatePreviewBoxProps } from "./TemplatePreviewBox";

interface TemplateEditingWindowProps {
    menu: DocCreatorMenu;
    template: Template;
    setupButtonClick: (e: React.PointerEvent, func: () => void) => void;
}

@observer
export class TemplateEditingWindow extends ObservableReactComponent<TemplateEditingWindowProps> {

    private fireflyPrompt: string = 'Use this template to generate an empty baseball card template.';
    private previewWindow: HTMLDivElement | null = null;
    private _disposers: { [name: string]: IDisposer } = {};

    @observable _loading: boolean = false;
    @observable _variationsTabOpen: boolean = false;
    @observable _variationURLs: string[] = [];
    @observable _variations: Template[] = [];

    componentDidMount(): void {
        this._disposers.windowDimensions = reaction(() => 
            this._props.menu._resizing, 
            () => { this.forceUpdate() }, 
            { fireImmediately: true }
            );
    }

    componentWillUnmount() {
        Object.values(this._disposers).forEach(disposer => disposer?.());
    }

    setContainerRef: React.LegacyRef<HTMLDivElement> = (node) => {
        this.previewWindow = node;
        this.forceUpdate();
    }

    @action setVariationTab = (open: boolean) => {
        this._variationsTabOpen = open;
        if (this.previewWindow && open) {
            this.previewWindow.style.height = String(Number(this.previewWindow.clientHeight) * .6);
        } else if (this.previewWindow && !open) {
            this.previewWindow.style.height = String(Number(this.previewWindow.clientHeight) * 5/3);
        }
    }

    func = () => {
        this._props.menu._variations.forEach(variation => {
            variation.setImageAsBackground('https://www.onthegotours.com/repository/Great-Wall-New-Pic-228551391689622.jpg', true)
        });
    }

    get fireflyVariationsTab() {

        return (
            <>
                <div className="docCreatorMenu-option-divider full no-margin-bottom"/>
                <TemplatePreviewGrid
                    menu={this._props.menu}
                    title={'Generate Variations'}
                    templates={this._props.menu._variations}
                    optionsButtonOpts={['gear', this.func]}
                    setupButtonClick={this._props.setupButtonClick}
                    previewBoxRightButtonOpts={['gear', (component: ObservableReactComponent<TemplatePreviewBoxProps>) => {component.forceUpdate();}]}
                />
                <div className="docCreatorMenu-section">
                    <div className="docCreatorMenu-variation-prompt-input">
                        <textarea
                            className="docCreatorMenu-variation-prompt-input-textbox"
                            onChange={e => this.fireflyPrompt = e.target.value}
                            defaultValue={''}
                            placeholder={'Enter a custom prompt here (optional)'}
                        />
                        <button className="docCreatorMenu-menu-button" 
                            onPointerDown={e => this._props.setupButtonClick(e, async () => {
                                this._props.menu._variations = [];
                                this._loading = true;
                                this._variationURLs = await this._props.menu.generateVariations(this._props.template.getRenderedDoc()!, this.fireflyPrompt);
                                const templates: Template[] = [];
                                this._variationURLs.forEach(url => {
                                    const newTemplate: Template = this._props.template.cloneBase();
                                    newTemplate.setImageAsBackground(url, true);
                                    templates.push(newTemplate);
                                });
                                this._loading = false;
                                setTimeout(() => {
                                    console.log('setting')
                                    this._props.menu._variations = templates;
                                    this.forceUpdate();
                                }, 1000);
                            })
                        }>
                            <FontAwesomeIcon icon="arrows-rotate" />
                        </button>
                    </div>
                </div>
            </>
        )
    }
   
    get renderedDocPreview(){
        const doc: Doc = this._props.template.getRenderedDoc() as unknown as Doc;

        return (
            <div className="docCreatorMenu-expanded-template-preview" ref={this.setContainerRef}>
                {this.previewWindow ? <DocumentView
                    Document={doc}
                    isContentActive={emptyFunction}
                    addDocument={returnFalse}
                    moveDocument={returnFalse}
                    removeDocument={returnFalse}
                    PanelWidth={() => this.previewWindow?.clientWidth ?? 500}
                    PanelHeight={() => this.previewWindow?.clientHeight ?? 500}
                    ScreenToLocalTransform={() => new Transform(-this._props.menu._pageX - 5, -this._props.menu._pageY - 35, 1)}
                    renderDepth={5}
                    whenChildContentsActiveChanged={emptyFunction}
                    focus={emptyFunction}
                    styleProvider={DefaultStyleProvider}
                    addDocTab={DocumentViewInternal.addDocTabFunc}
                    pinToPres={() => undefined}
                    childFilters={returnEmptyFilter}
                    childFiltersByRanges={returnEmptyFilter}
                    searchFilterDocs={returnEmptyDoclist}
                    fitContentsToBox={returnFalse}
                    fitWidth={returnFalse}
                /> : null}
            </div>
        )
    }

    render() {
        return (
            <div className='docCreatorMenu-templates-view'>
                <div className="docCreatorMenu-expanded-template-preview">
                    <div className="top-panel"/>
                    {this.renderedDocPreview}
                    {this._variationsTabOpen ? this.fireflyVariationsTab : null}
                    <div className="right-buttons-panel">
                        <button
                            className="docCreatorMenu-menu-button section-reveal-options top-right"
                            onPointerDown={e =>
                                this._props.setupButtonClick(e, () => {
                                    if (this._props.template === this._props.menu._selectedTemplate) {
                                        this._props.menu.updateRenderedPreviewCollection(this._props.template);
                                    }
                                    this._props.menu.setExpandedView(undefined);
                                })
                            }>
                            <FontAwesomeIcon icon="minimize" />
                        </button>
                        <button className="docCreatorMenu-menu-button section-reveal-options top-right" onPointerDown={e => this._props.setupButtonClick(e, async () => {
                                this.setVariationTab(!this._variationsTabOpen);
                                // this._props.template.setImageAsBackground('https://www.onthegotours.com/repository/Great-Wall-New-Pic-228551391689622.jpg', true);
                                this.forceUpdate();
                            })}>
                            <FontAwesomeIcon icon="lightbulb" />
                        </button>
                    </div>
                </div>
            </div>
        );
    }
}