import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IconButton, Size } from '@dash/components';
import * as faceapi from 'face-api.js';
import { FaceMatcher } from 'face-api.js';
import 'ldrs/ring';
import { IReactionDisposer, action, makeObservable, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { DivHeight, lightOrDark, returnTrue, setupMoveUpEvents } from '../../../../ClientUtils';
import { emptyFunction } from '../../../../Utils';
import { Doc, DocListCast, Opt } from '../../../../fields/Doc';
import { DocData } from '../../../../fields/DocSymbols';
import { List } from '../../../../fields/List';
import { DocCast, ImageCastToNameType, NumCast, StrCast } from '../../../../fields/Types';
import { DocumentType } from '../../../documents/DocumentTypes';
import { Docs } from '../../../documents/Documents';
import { DragManager } from '../../../util/DragManager';
import { dropActionType } from '../../../util/DropActionTypes';
import { undoable } from '../../../util/UndoManager';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { DocumentView } from '../../nodes/DocumentView';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { FaceRecognitionHandler } from '../../search/FaceRecognitionHandler';
import { CollectionStackingView } from '../CollectionStackingView';
import './FaceCollectionBox.scss';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
import { returnEmptyDocViewList } from '../../StyleProvider';

/**
 * This code is used to render the sidebar collection of unique recognized faces, where each
 * unique face in turn displays the set of images that correspond to the face.
 */

/**
 * Viewer for unique face Doc collections.
 *
 * This both displays a collection of images corresponding tp a unique face, and
 * allows for editing the face collection by removing an image, or drag-and-dropping
 * an image that was not recognized.
 */
@observer
export class UniqueFaceBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(UniqueFaceBox, fieldKey);
    }
    private _dropDisposer?: DragManager.DragDropDisposer;
    private _disposers: { [key: string]: IReactionDisposer } = {};
    private _lastHeight = 0;

    constructor(props: FieldViewProps) {
        super(props);
        makeObservable(this);
    }

    @observable _headerRef: HTMLDivElement | null = null;
    @observable _listRef: HTMLDivElement | null = null;

    observer = new ResizeObserver(() => {
        this._props.setHeight?.(
            (this.props.Document._face_showImages ? 20 : 0) + //
                (!this._headerRef ? 0 : DivHeight(this._headerRef)) +
                (!this._listRef ? 0 : DivHeight(this._listRef))
        );
    });

    componentDidMount(): void {
        this._disposers.refList = reaction(
            () => ({ refList: [this._headerRef, this._listRef], autoHeight: this.layoutDoc._layout_autoHeight }),
            ({ refList, autoHeight }) => {
                this.observer.disconnect();
                if (autoHeight) refList.filter(r => r).forEach(r => this.observer.observe(r!));
            },
            { fireImmediately: true }
        );
    }

    componentWillUnmount(): void {
        this.observer.disconnect();
        Object.keys(this._disposers).forEach(key => this._disposers[key]());
    }

    protected createDropTarget = (ele: HTMLDivElement) => {
        this._dropDisposer?.();
        ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.Document));
    };

    protected onInternalDrop(e: Event, de: DragManager.DropEvent): boolean {
        de.complete.docDragData?.droppedDocuments
            ?.filter(doc => doc.type === DocumentType.IMG)
            .forEach(imgDoc => {
                // If the current Face Document has no faces, and the doc has more than one face descriptor, don't let the user add the document first.  Or should we just use the first face ?
                if (FaceRecognitionHandler.UniqueFaceDescriptors(this.Document).length === 0 && FaceRecognitionHandler.ImageDocFaceAnnos(imgDoc).length > 1) {
                    alert('Cannot add a document with multiple faces as the first item!');
                } else {
                    // Loop through the documents' face descriptors and choose the face in the iage with the smallest distance (most similar to the face colleciton)
                    const faceDescriptorsAsFloat32Array = FaceRecognitionHandler.UniqueFaceDescriptors(this.Document).map(fd => new Float32Array(Array.from(fd)));
                    const labeledFaceDescriptor = new faceapi.LabeledFaceDescriptors(FaceRecognitionHandler.UniqueFaceLabel(this.Document), faceDescriptorsAsFloat32Array);
                    const faceMatcher = new FaceMatcher([labeledFaceDescriptor], 1);
                    const faceAnno =
                        FaceRecognitionHandler.ImageDocFaceAnnos(imgDoc).reduce(
                            (prev, fAnno) => {
                                const match = faceMatcher.matchDescriptor(new Float32Array(Array.from(fAnno.faceDescriptor as List<number>)));
                                return match.distance < prev.dist ? { dist: match.distance, faceAnno: fAnno } : prev;
                            },
                            { dist: 1, faceAnno: undefined as Opt<Doc> }
                        ).faceAnno ?? imgDoc;

                    // assign the face in the image that's closest to the face collection's face
                    if (faceAnno) {
                        DocCast(faceAnno.face) && FaceRecognitionHandler.UniqueFaceRemoveFaceImage(faceAnno, DocCast(faceAnno.face)!);
                        FaceRecognitionHandler.UniqueFaceAddFaceImage(faceAnno, this.Document);
                        faceAnno.$face = this.Document[DocData];
                    }
                }
            });
        de.complete.docDragData?.droppedDocuments
            ?.filter(doc => DocCast(doc.face)?.type === DocumentType.UFACE)
            .forEach(faceAnno => {
                const imgDoc = faceAnno;
                DocCast(faceAnno.face) && FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, DocCast(faceAnno.face)!);
                FaceRecognitionHandler.UniqueFaceAddFaceImage(faceAnno, this.Document);
                faceAnno.$face = this.Document[DocData];
            });
        e.stopPropagation();
        return true;
    }

    /**
     * Toggles whether a Face Document displays its associated docs.  This saves and restores the last height of the Doc since
     * toggling the associated Documentss overwrites the Doc height.
     */
    onDisplayClick() {
        this.Document._face_showImages && (this._lastHeight = NumCast(this.Document.height));
        this.Document._face_showImages = !this.Document._face_showImages;
        setTimeout(action(() => (!this.Document.layout_autoHeight || !this.Document._face_showImages) && (this.Document.height = this.Document._face_showImages ? this._lastHeight : 60)));
    }

    /**
     * Removes a unique face Doc from the colelction of unique faces.
     */
    deleteUniqueFace = undoable(() => {
        FaceRecognitionHandler.DeleteUniqueFace(this.Document);
    }, 'delete face');

    /**
     * Removes a face image Doc from a unique face's list of images.
     * @param imgDoc - image Doc to remove
     */
    removeFaceImageFromUniqueFace = undoable((imgDoc: Doc) => {
        FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, this.Document);
    }, 'remove doc from face');

    setRef = (r: HTMLDivElement | null) => this.fixWheelEvents(r, this._props.isContentActive);
    render() {
        return (
            <div className="face-document-item" ref={ele => this.createDropTarget(ele!)}>
                <div className="face-collection-buttons">
                    <IconButton tooltip="Delete Face From Collection" onPointerDown={this.deleteUniqueFace} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
                </div>
                <div className="face-document-top" ref={action((r: HTMLDivElement | null) => (this._headerRef = r))}>
                    <h1 style={{ color: lightOrDark(StrCast(this.Document.backgroundColor)) }}>
                        <input className="face-document-name" type="text" onChange={e => FaceRecognitionHandler.SetUniqueFaceLabel(this.Document, e.currentTarget.value)} value={FaceRecognitionHandler.UniqueFaceLabel(this.Document)} />
                    </h1>
                </div>
                <div className="face-collection-toggle">
                    <IconButton
                        tooltip="See image information"
                        onPointerDown={() => this.onDisplayClick()}
                        icon={<FontAwesomeIcon icon={this.Document._face_showImages ? 'caret-up' : 'caret-down'} />}
                        color={MarqueeOptionsMenu.Instance.userColor}
                        style={{ width: '19px' }}
                    />
                </div>
                {this.props.Document._face_showImages ? (
                    <div
                        className="face-document-image-container"
                        style={{
                            pointerEvents: this._props.isContentActive() ? undefined : 'none',
                        }}
                        ref={this.setRef}>
                        {FaceRecognitionHandler.UniqueFaceImages(this.Document).map((doc, i) => {
                            const [name, type] = ImageCastToNameType(doc?.[Doc.LayoutDataKey(doc)]) ?? ['-missing-', '.png'];
                            return (
                                <div
                                    className="image-wrapper"
                                    key={i}
                                    onPointerDown={e =>
                                        setupMoveUpEvents(
                                            this,
                                            e,
                                            () => {
                                                const dragDoc = DocListCast(doc?.data_annotations).find(a => a.face === this.Document[DocData]) ?? this.Document;
                                                DragManager.StartDocumentDrag([e.target as HTMLElement], new DragManager.DocumentDragData([dragDoc], dropActionType.embed), e.clientX, e.clientY);
                                                return true;
                                            },
                                            emptyFunction,
                                            emptyFunction
                                        )
                                    }>
                                    <img onClick={() => doc && DocumentView.showDocument(doc, { willZoomCentered: true })} style={{ maxWidth: '60px', margin: '10px' }} src={`${name}_o.${type}`} />
                                    <div className="remove-item">
                                        <IconButton tooltip={'Remove Doc From Face Collection'} onPointerDown={() => this.removeFaceImageFromUniqueFace(doc)} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                ) : null}
            </div>
        );
    }
}

/**
 * This renders the sidebar collection of the unique faces that have been recognized.
 *
 * Since the collection of recognized faces is stored on the active dashboard, this class
 * does not itself store any Docs, but accesses the myUniqueFaces field of the current
 * dashboard.  (This should probably go away as Doc type in favor of it just being a
 * stacking collection of uniqueFace docs)
 */
@observer
export class FaceCollectionBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(FaceCollectionBox, fieldKey);
    }

    constructor(props: FieldViewProps) {
        super(props);
        makeObservable(this);
    }

    moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => !!(this._props.removeDocument?.(doc) && addDocument?.(doc));
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    addDocument = (doc: Doc | Doc[], annotationKey?: string) => {
        const uniqueFaceDoc = doc instanceof Doc ? doc : doc[0];
        const added = uniqueFaceDoc.type === DocumentType.UFACE;
        if (added) {
            Doc.MyFaceCollection && Doc.SetContainer(uniqueFaceDoc, Doc.MyFaceCollection);
            Doc.ActiveDashboard && Doc.AddDocToList(Doc.ActiveDashboard[DocData], 'myUniqueFaces', uniqueFaceDoc);
        }
        return added;
    };
    /**
     * this changes style provider requests that target the dashboard to requests that target the face collection box which is what's actually being rendered.
     * This is needed, for instance, to get the default background color from the face collection, not the dashboard.
     */
    stackingStyleProvider = (doc: Doc | undefined, props: Opt<FieldViewProps>, property: string) => {
        if (doc === Doc.ActiveDashboard) return this._props.styleProvider?.(this.Document, this._props, property);
        return this._props.styleProvider?.(doc, this._props, property);
    };

    render() {
        return !Doc.ActiveDashboard ? null : (
            <div className="faceCollectionBox">
                <div className="documentButtonMenu">
                    <div className="documentExplanation" onClick={action(() => (Doc.UserDoc().recognizeFaceImages = !Doc.UserDoc().recognizeFaceImages))}>{`Face Recgognition is ${Doc.UserDoc().recognizeFaceImages ? 'on' : 'off'}`}</div>
                </div>
                <CollectionStackingView
                    {...this._props} //
                    styleProvider={this.stackingStyleProvider}
                    Document={Doc.ActiveDashboard}
                    DocumentView={undefined}
                    docViewPath={returnEmptyDocViewList}
                    fieldKey="myUniqueFaces"
                    moveDocument={this.moveDocument}
                    addDocument={this.addDocument}
                    isContentActive={returnTrue}
                    isAnyChildContentActive={returnTrue}
                    childHideDecorations={true}
                    dontCenter="y"
                />
            </div>
        );
    }
}

Docs.Prototypes.TemplateMap.set(DocumentType.FACECOLLECTION, {
    layout: { view: FaceCollectionBox, dataField: 'data' },
    options: { acl: '', _width: 400, dropAction: dropActionType.embed },
});

Docs.Prototypes.TemplateMap.set(DocumentType.UFACE, {
    layout: { view: UniqueFaceBox, dataField: 'face_images' },
    options: { acl: '', _width: 400, _height: 400 },
});
