import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Tooltip } from '@material-ui/core';
import { action, IReactionDisposer, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc, Opt } from '../../../../fields/Doc';
import { Height, Width } from '../../../../fields/DocSymbols';
import { Id } from '../../../../fields/FieldSymbols';
import { BoolCast, Cast, DocCast, NumCast, ScriptCast, StrCast } from '../../../../fields/Types';
import { emptyFunction, returnEmptyDoclist, returnTrue, StopEvent, Utils } from '../../../../Utils';
import { CollectionViewType } from '../../../documents/DocumentTypes';
import { DocumentManager } from '../../../util/DocumentManager';
import { DragManager, dropActionType } from '../../../util/DragManager';
import { Transform } from '../../../util/Transform';
import { DocumentLinksButton } from '../../nodes/DocumentLinksButton';
import { DocumentView } from '../../nodes/DocumentView';
import { LinkDescriptionPopup } from '../../nodes/LinkDescriptionPopup';
import { StyleProp } from '../../StyleProvider';
import { UndoStack } from '../../UndoStack';
import { CollectionStackedTimeline } from '../CollectionStackedTimeline';
import { CollectionSubView } from '../CollectionSubView';
import './CollectionLinearView.scss';
import { Button, Toggle, ToggleType, Type } from 'browndash-components';
import { Colors } from '../../global/globalEnums';

/**
 * CollectionLinearView is the class for rendering the horizontal collection
 * of documents, it useful for horizontal menus. It can either be expandable
 * or not using the linearView_Expandable field.
 * It is used in the following locations:
 * - It is used in the popup menu on the bottom left (see docButtons() in MainView.tsx)
 * - It is used for the context sensitive toolbar at the top (see contMenuButtons() in CollectionMenu.tsx)
 */
@observer
export class CollectionLinearView extends CollectionSubView() {
    @observable public addMenuToggle = React.createRef<HTMLInputElement>();
    @observable private _selectedIndex = -1;
    private _dropDisposer?: DragManager.DragDropDisposer;
    private _widthDisposer?: IReactionDisposer;
    private _selectedDisposer?: IReactionDisposer;

    componentWillUnmount() {
        this._dropDisposer?.();
        this._widthDisposer?.();
        this._selectedDisposer?.();
        this.childLayoutPairs.map((pair, ind) => ScriptCast(DocCast(pair.layout.proto)?.onPointerUp)?.script.run({ this: pair.layout.proto }, console.log));
    }

    componentDidMount() {
        this._widthDisposer = reaction(
            () => 5 + NumCast(this.rootDoc.linearBtnWidth, this.dimension()) + (this.layoutDoc.linearView_IsOpen ? this.childDocs.filter(doc => !doc.hidden).reduce((tot, doc) => (doc[Width]() || this.dimension()) + tot + 4, 0) : 0),
            width => this.childDocs.length && (this.layoutDoc._width = width),
            { fireImmediately: true }
        );
    }
    protected createDashEventsTarget = (ele: HTMLDivElement | null) => {
        this._dropDisposer?.();
        if (ele) this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc);
    };

    dimension = () => NumCast(this.rootDoc._height);
    getTransform = (ele: Opt<HTMLDivElement>) => {
        if (!ele) return Transform.Identity();
        const { scale, translateX, translateY } = Utils.GetScreenTransform(ele);
        return new Transform(-translateX, -translateY, 1);
    };

    @action
    exitLongLinks = () => {
        if (DocumentLinksButton.StartLink?.Document) {
            action((e: React.PointerEvent<HTMLDivElement>) => Doc.UnBrushDoc(DocumentLinksButton.StartLink?.Document as Doc));
        }
        DocumentLinksButton.StartLink = undefined;
        DocumentLinksButton.StartLinkView = undefined;
    };

    @action
    changeDescriptionSetting = () => {
        if (LinkDescriptionPopup.showDescriptions) {
            if (LinkDescriptionPopup.showDescriptions === 'ON') {
                LinkDescriptionPopup.showDescriptions = 'OFF';
                LinkDescriptionPopup.descriptionPopup = false;
            } else {
                LinkDescriptionPopup.showDescriptions = 'ON';
            }
        } else {
            LinkDescriptionPopup.showDescriptions = 'OFF';
            LinkDescriptionPopup.descriptionPopup = false;
        }
    };

    myContextMenu = (e: React.MouseEvent) => {
        e.stopPropagation();
        e.preventDefault();
    };

    getLinkUI = () => {
        return !DocumentLinksButton.StartLink ? null : (
            <span className="bottomPopup-background" style={{ pointerEvents: 'all' }} onPointerDown={e => e.stopPropagation()}>
                <span className="bottomPopup-text">
                    Creating link from:{' '}
                    <b>
                        {(DocumentLinksButton.AnnotationId ? 'Annotation in ' : ' ') +
                            (StrCast(DocumentLinksButton.StartLink.title).length < 51 ? DocumentLinksButton.StartLink.title : StrCast(DocumentLinksButton.StartLink.title).slice(0, 50) + '...')}
                    </b>
                </span>

                <Tooltip title={<div className="dash-tooltip">{'Toggle description pop-up'} </div>} placement="top">
                    <span className="bottomPopup-descriptions" onClick={this.changeDescriptionSetting}>
                        Labels: {LinkDescriptionPopup.showDescriptions ? LinkDescriptionPopup.showDescriptions : 'ON'}
                    </span>
                </Tooltip>

                <Tooltip title={<div className="dash-tooltip">Exit linking mode</div>} placement="top">
                    <span className="bottomPopup-exit" onClick={this.exitLongLinks}>
                        Stop
                    </span>
                </Tooltip>
            </span>
        );
    };
    getCurrentlyPlayingUI = () => {
        return !CollectionStackedTimeline.CurrentlyPlaying?.length ? null : (
            <span className="bottomPopup-background">
                <span className="bottomPopup-text">
                    Currently playing:
                    {CollectionStackedTimeline.CurrentlyPlaying.map((clip, i) => (
                        <>
                            <span className="audio-title" onPointerDown={() => DocumentManager.Instance.showDocument(clip.rootDoc, { willZoomCentered: true })}>
                                {clip.rootDoc.title + (i === CollectionStackedTimeline.CurrentlyPlaying.length - 1 ? '  ' : ',')}
                            </span>
                            <FontAwesomeIcon icon={!clip.ComponentView?.IsPlaying?.() ? 'play' : 'pause'} size="lg" onPointerDown={() => clip.ComponentView?.TogglePause?.()} />{' '}
                            <FontAwesomeIcon icon="times" size="lg" onPointerDown={() => clip.ComponentView?.Pause?.()} />{' '}
                        </>
                    ))}
                </span>
            </span>
        );
    };

    getDisplayDoc = (doc: Doc, preview: boolean = false) => {
        // hack to avoid overhead of making UndoStack,etc into DocumentView style Boxes. If the UndoStack is ever intended to become part of the persisten state of the dashboard, then this would have to change.
        // prettier-ignore
        switch (doc.layout) {
            case '<LinkingUI>':          return this.getLinkUI();
            case '<CurrentlyPlayingUI>': return this.getCurrentlyPlayingUI();
            case '<UndoStack>':          return <UndoStack key={doc[Id]} width={200} height={40} inline={true} />;
        }

        const nested = doc._type_collection === CollectionViewType.Linear;
        const hidden = doc.hidden === true;

        let dref: Opt<HTMLDivElement>;
        const docXf = () => this.getTransform(dref);
        // const scalable = pair.layout.onClick || pair.layout.onDragStart;
        return hidden ? null : (
            <div
                className={preview ? 'preview' : `collectionLinearView-docBtn`}
                key={doc[Id]}
                ref={r => (dref = r || undefined)}
                style={{
                    pointerEvents: 'all',
                    width: NumCast(doc._width),
                    height: NumCast(doc._height),
                    marginLeft: 2,
                    marginRight: 2,
                    // width: NumCast(pair.layout._width),
                    // height: NumCast(pair.layout._height),
                }}>
                <DocumentView
                    Document={doc}
                    isContentActive={this.props.isContentActive}
                    isDocumentActive={returnTrue}
                    addDocument={this.props.addDocument}
                    moveDocument={this.props.moveDocument}
                    addDocTab={this.props.addDocTab}
                    pinToPres={emptyFunction}
                    dragAction={(this.layoutDoc.childDragAction ?? this.props.childDragAction) as dropActionType}
                    rootSelected={this.props.isSelected}
                    removeDocument={this.props.removeDocument}
                    ScreenToLocalTransform={docXf}
                    PanelWidth={doc[Width]}
                    PanelHeight={nested || doc._height ? doc[Height] : this.dimension}
                    renderDepth={this.props.renderDepth + 1}
                    dontRegisterView={BoolCast(this.rootDoc.childDontRegisterViews)}
                    focus={emptyFunction}
                    styleProvider={this.props.styleProvider}
                    docViewPath={returnEmptyDoclist}
                    whenChildContentsActiveChanged={emptyFunction}
                    bringToFront={emptyFunction}
                    childFilters={this.props.childFilters}
                    childFiltersByRanges={this.props.childFiltersByRanges}
                    searchFilterDocs={this.props.searchFilterDocs}
                    hideResizeHandles={true}
                />
            </div>
        );
    };

    render() {
        const flexDir = StrCast(this.Document.flexDirection); // Specify direction of linear view content
        const flexGap = NumCast(this.Document.flexGap); // Specify the gap between linear view content
        const isExpanded = BoolCast(this.layoutDoc.linearView_IsOpen);

        const menuOpener = (
            <Toggle
                text={Cast(this.props.Document.icon, 'string', null)}
                icon={Cast(this.props.Document.icon, 'string', null) ? undefined : <FontAwesomeIcon icon={isExpanded ? 'minus' : 'plus'} />}
                type={Type.TERT}
                color={StrCast(Doc.UserDoc().userVariantColor, Colors.MEDIUM_BLUE)}
                onPointerDown={e => e.stopPropagation()}
                toggleType={ToggleType.BUTTON}
                toggleStatus={BoolCast(this.layoutDoc.linearView_IsOpen)}
                onClick={() => {
                    this.layoutDoc.linearView_IsOpen = !isExpanded;
                }}
                tooltip={isExpanded ? 'Close' : 'Open'}
                fillWidth={true}
                align={'center'}
            />
        );

        return (
            <div className={`collectionLinearView-outer ${this.layoutDoc.linearView_SubMenu}`} style={{ backgroundColor: this.layoutDoc.linearView_IsOpen ? undefined : 'transparent' }}>
                <div className="collectionLinearView" ref={this.createDashEventsTarget} onContextMenu={this.myContextMenu} style={{ minHeight: this.dimension(), pointerEvents: 'all' }}>
                    {
                        <>
                            {menuOpener}
                            {!this.layoutDoc.linearView_IsOpen ? null : (
                                <div
                                    className="collectionLinearView-content"
                                    style={{
                                        height: this.dimension(),
                                        flexDirection: flexDir as any,
                                        gap: flexGap,
                                    }}>
                                    {this.childLayoutPairs.map(pair => this.getDisplayDoc(pair.layout))}
                                </div>
                            )}
                        </>
                    }
                </div>
            </div>
        );
    }
}
