import { action, observable } from 'mobx';
import { observer } from 'mobx-react';
import { Doc } from '../../../fields/Doc';
import { LinkManager } from '../../util/LinkManager';
import { DocumentView } from '../nodes/DocumentView';
import { LinkDocPreview } from '../nodes/LinkDocPreview';
import './LinkMenu.scss';
import { LinkMenuGroup } from './LinkMenuGroup';
import * as React from 'react';
import { SettingsManager } from '../../util/SettingsManager';

interface Props {
    docView: DocumentView;
    style?: { left: number; top: number };
    itemHandler?: (doc: Doc) => void;
    clearLinkEditor?: () => void;
}

/**
 * the outermost component for the link menu of a node that contains a list of its linked nodes
 */
@observer
export class LinkMenu extends React.Component<Props> {
    _editorRef = React.createRef<HTMLDivElement>();
    @observable _linkMenuRef = React.createRef<HTMLDivElement>();

    clear = () => this.props.clearLinkEditor?.();

    componentDidMount() {
        this.props.clearLinkEditor && document.addEventListener('pointerdown', this.onPointerDown, true);
    }
    componentWillUnmount() {
        this.props.clearLinkEditor && document.removeEventListener('pointerdown', this.onPointerDown, true);
    }

    onPointerDown = action((e: PointerEvent) => {
        LinkDocPreview.Clear();
        if (!this._linkMenuRef.current?.contains(e.target as any) && !this._editorRef.current?.contains(e.target as any)) {
            this.clear();
        }
    });

    /**
     * maps each link to a JSX element to be rendered
     * @param groups containing info of all of the links
     * @returns list of link JSX elements if there at least one linked element
     */
    renderAllGroups = (groups: Map<string, Array<Doc>>): Array<JSX.Element> => {
        const linkItems = Array.from(groups.entries()).map(group => (
            <LinkMenuGroup key={group[0]} itemHandler={this.props.itemHandler} docView={this.props.docView} sourceDoc={this.props.docView.props.Document} group={group[1]} groupType={group[0]} clearLinkEditor={this.clear} />
        ));

        return linkItems.length ? linkItems : this.props.style ? [] : [<p key="none">No links have been created yet. Drag the linking button onto another document to create a link.</p>];
    };

    render() {
        const sourceDoc = this.props.docView.Document;
        const sourceAnchor = this.props.docView.anchorViewDoc ?? sourceDoc;
        const style = this.props.style ?? (dv => ({ left: dv?.left || 0, top: this.props.docView.topMost ? undefined : (dv?.bottom || 0) + 15, bottom: this.props.docView.topMost ? 20 : undefined, maxWidth: 200 }))(this.props.docView.getBounds());

        return (
            <div className="linkMenu" ref={this._linkMenuRef} style={{ ...style, background: SettingsManager.userBackgroundColor, color: SettingsManager.userColor }}>
                <div className="linkMenu-list">{this.renderAllGroups(LinkManager.Instance.getRelatedGroupedLinks(sourceAnchor))}</div>
            </div>
        );
    }
}
