import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Colors, IconButton } from 'browndash-components';
import { action, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { Doc } from '../../../../fields/Doc';
import { Docs } from '../../../documents/Documents';
import { DocumentType } from '../../../documents/DocumentTypes';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
import './ImageLabelBox.scss';
import { MainView } from '../../MainView';
import { MarqueeView } from './MarqueeView';
import 'ldrs/ring';
import { ring } from 'ldrs';
import { SnappingManager } from '../../../util/SnappingManager';
import { ImageCast } from '../../../../fields/Types';
import { DocData } from '../../../../fields/DocSymbols';

@observer
export class ImageLabelBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(ImageLabelBox, fieldKey);
    }

    public static Instance: ImageLabelBox | null = null;
    private _inputRef = React.createRef<HTMLInputElement>();
    @observable _loading: boolean = true;
    @observable _currentLabel: string = '';
    @observable _labelGroups: string[] = [];
    @observable _selectedImages: Doc[] = [];
    @observable _displayImageInformation: boolean = false;

    constructor(props: any) {
        super(props);
        makeObservable(this);
        ImageLabelBox.Instance = this;
        ring.register();
        console.log('Image Box Has Been Initialized');
    }

    /**
     * This method is called when the SearchBox component is first mounted. When the user opens
     * the search panel, the search input box is automatically selected. This allows the user to
     * type in the search input box immediately, without needing clicking on it first.
     */
    componentDidMount() {
        // if (this._inputRef.current) {
        //     this._inputRef.current.focus();
        // }
    }

    @action
    addLabel = (label: string) => {
        label = label.toUpperCase().trim();
        if (label.length > 0) {
            if (!this._labelGroups.includes(label)) {
                this._labelGroups = [...this._labelGroups, label];
            }
        }
    };

    @action
    removeLabel = (label: string) => {
        const labelUp = label.toUpperCase();
        this._labelGroups = this._labelGroups.filter(group => group !== labelUp);
    };

    @action
    groupImages = () => {
        MarqueeOptionsMenu.Instance.groupImages();
        this._labelGroups = [];
        MainView.Instance.closeFlyout();
    };

    @action
    startLoading = () => {
        this._loading = true;
    };

    @action
    endLoading = () => {
        this._loading = false;
    };

    @action
    setSelectedImages = (selected: Doc[]) => {
        this._selectedImages = selected;
    };

    render() {
        if (this._loading) {
            return (
                <div className="image-box-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
                    <l-ring size="60" color="white" />
                </div>
            );
        }

        return (
            <div className="searchBox-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
                <div className="searchBox-bar" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
                    <IconButton
                        tooltip={'See image information'}
                        onPointerDown={() => {
                            this._displayImageInformation = !this._displayImageInformation;
                        }}
                        icon={this._displayImageInformation ? <FontAwesomeIcon icon="caret-up" /> : <FontAwesomeIcon icon="caret-down" />}
                        color={MarqueeOptionsMenu.Instance.userColor}
                        style={{ width: '19px' }}
                    />
                    <input
                        defaultValue=""
                        autoComplete="off"
                        // onKeyDown={e => {
                        //     e.key === 'Enter' ? this.submitSearch() : null;
                        //     e.stopPropagation();
                        // }}
                        type="text"
                        placeholder="Input labels for image groupings..."
                        aria-label="label-input"
                        id="new-label"
                        className="searchBox-input"
                        style={{ width: '100%', borderRadius: '5px' }}
                        ref={this._inputRef}
                    />
                    <IconButton
                        tooltip={'Add a label'}
                        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' }}
                    />
                    {this._labelGroups.length > 0 ? <IconButton tooltip={'Group Images'} onPointerDown={this.groupImages} icon={<FontAwesomeIcon icon="object-group" />} color={Colors.MEDIUM_BLUE} style={{ width: '19px' }} /> : <div></div>}
                </div>
                <div>
                    <div className="image-label-list">
                        {this._labelGroups.map(group => {
                            return (
                                <div>
                                    <p style={{ color: MarqueeOptionsMenu.Instance.userColor }}>{group}</p>
                                    <IconButton
                                        tooltip={'Remove Label'}
                                        onPointerDown={() => {
                                            this.removeLabel(group);
                                        }}
                                        icon={'x'}
                                        color={MarqueeOptionsMenu.Instance.userColor}
                                        style={{ width: '8px' }}
                                    />
                                </div>
                            );
                        })}
                    </div>
                </div>
                {this._displayImageInformation ? (
                    <div className="image-information">
                        {this._selectedImages.map(doc => {
                            const [name, type] = ImageCast(doc[Doc.LayoutFieldKey(doc)]).url.href.split('.');
                            return (
                                <div>
                                    <img src={`${name}_o.${type}`}></img>
                                    {(doc[DocData].data_labels as string).split('\n').map(label => {
                                        return <div className="image-label">{label}</div>;
                                    })}
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    <div></div>
                )}
            </div>
        );
    }
}

Docs.Prototypes.TemplateMap.set(DocumentType.IMAGEGROUPER, {
    layout: { view: ImageLabelBox, dataField: 'data' },
    options: { acl: '', _width: 400 },
});
