import { action } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc } from '../../fields/Doc';
import { DocCast } from '../../fields/Types';
import { DocumentType } from '../documents/DocumentTypes';
import { LinkManager } from '../util/LinkManager';
import { SettingsManager } from '../util/SettingsManager';
import './PropertiesDocBacklinksSelector.scss';
import { CollectionDockingView } from './collections/CollectionDockingView';
import { LinkMenu } from './linking/LinkMenu';
import { DocumentView } from './nodes/DocumentView';
import { OpenWhere } from './nodes/OpenWhere';

type PropertiesDocBacklinksSelectorProps = {
    Document: Doc;
    Stack?: string;
    hideTitle?: boolean;
    addDocTab(doc: Doc, location: OpenWhere): void;
};

@observer
export class PropertiesDocBacklinksSelector extends React.Component<PropertiesDocBacklinksSelectorProps> {
    getOnClick = action((link: Doc) => {
        const linkAnchor = this.props.Document;
        const other = Doc.getOppositeAnchor(link, linkAnchor);
        const otherdoc = !other ? undefined : other.annotationOn && other.type !== DocumentType.RTF ? DocCast(other.annotationOn) : other;
        LinkManager.Instance.currentLink = link;
        if (otherdoc) {
            otherdoc.hidden = false;
            this.props.addDocTab(Doc.IsDataProto(otherdoc) ? Doc.MakeDelegate(otherdoc) : otherdoc, OpenWhere.toggleRight);
            CollectionDockingView.Instance?.endUndoBatch();
        }
    });

    render() {
        return !DocumentView.Selected().length ? null : (
            <div className="propertiesDocBacklinksSelector" style={{ color: SettingsManager.userColor, backgroundColor: SettingsManager.userBackgroundColor }}>
                {this.props.hideTitle ? null : <p key="contexts">Contexts:</p>}
                <LinkMenu docView={DocumentView.Selected().lastElement()} clearLinkEditor={undefined} itemHandler={this.getOnClick} style={{ left: 0, top: 0 }} />
            </div>
        );
    }
}
