import { action, makeObservable, observable, toJS } from 'mobx';
import { observer } from 'mobx-react';
import { Doc, Field } from '../../../fields/Doc';
import { copyProps, emptyFunction, returnEmptyDoclist, returnEmptyFilter, returnFalse, returnZero } from '../../../Utils';
import { Transform } from '../../util/Transform';
import { undoBatch } from '../../util/UndoManager';
import { ContextMenu } from '../ContextMenu';
import { EditableView } from '../EditableView';
import { DefaultStyleProvider } from '../StyleProvider';
import { OpenWhere, OpenWhereMod } from './DocumentView';
import { FieldView, FieldViewProps } from './FieldView';
import { KeyValueBox } from './KeyValueBox';
import './KeyValueBox.scss';
import './KeyValuePair.scss';
import * as React from 'react';
import { DocCast } from '../../../fields/Types';
import { Tooltip } from '@mui/material';
import { DocumentOptions, FInfo } from '../../documents/Documents';

// Represents one row in a key value plane

export interface KeyValuePairProps {
    rowStyle: string;
    keyName: string;
    doc: Doc;
    keyWidth: number;
    PanelHeight: () => number;
    PanelWidth: () => number;
    addDocTab: (doc: Doc, where: OpenWhere) => boolean;
}
@observer
export class KeyValuePair extends React.Component<KeyValuePairProps> {
    @observable private isPointerOver = false;
    @observable public isChecked = false;
    private checkbox = React.createRef<HTMLInputElement>();

    _prevProps: KeyValuePairProps;
    @observable _props: KeyValuePairProps;
    constructor(props: KeyValuePairProps) {
        super(props);
        this._props = this._prevProps = props;
        makeObservable(this);
    }

    componentDidUpdate() {
        copyProps(this);
    }

    @action
    handleCheck = (e: React.ChangeEvent<HTMLInputElement>) => {
        this.isChecked = e.currentTarget.checked;
    };

    @action
    uncheck = () => {
        this.checkbox.current!.checked = false;
        this.isChecked = false;
    };

    onContextMenu = (e: React.MouseEvent) => {
        const value = this._props.doc[this._props.keyName];
        if (value instanceof Doc) {
            e.stopPropagation();
            e.preventDefault();
            ContextMenu.Instance.addItem({ description: 'Open Fields', event: () => this._props.addDocTab(value, OpenWhere.addRightKeyvalue), icon: 'layer-group' });
            ContextMenu.Instance.displayMenu(e.clientX, e.clientY);
        }
    };

    render() {
        const props: FieldViewProps = {
            Document: this._props.doc,
            childFilters: returnEmptyFilter,
            childFiltersByRanges: returnEmptyFilter,
            searchFilterDocs: returnEmptyDoclist,
            styleProvider: DefaultStyleProvider,
            docViewPath: returnEmptyDoclist,
            fieldKey: this._props.keyName,
            isSelected: returnFalse,
            setHeight: returnFalse,
            select: emptyFunction,
            bringToFront: emptyFunction,
            renderDepth: 1,
            isContentActive: returnFalse,
            whenChildContentsActiveChanged: emptyFunction,
            ScreenToLocalTransform: Transform.Identity,
            focus: emptyFunction,
            PanelWidth: this._props.PanelWidth,
            PanelHeight: this._props.PanelHeight,
            addDocTab: returnFalse,
            pinToPres: returnZero,
        };
        // let fieldKey = Object.keys(props.Document).indexOf(props.fieldKey) !== -1 ? props.fieldKey : "(" + props.fieldKey + ")";
        let protoCount = 0;
        let doc: Doc | undefined = props.Document;
        while (doc) {
            if (Object.keys(doc).includes(props.fieldKey)) {
                break;
            }
            protoCount++;
            doc = DocCast(doc.proto);
        }
        const parenCount = Math.max(0, protoCount - 1);
        const keyStyle = protoCount === 0 ? 'black' : 'blue';

        const hover = { transition: '0.3s ease opacity', opacity: this.isPointerOver || this.isChecked ? 1 : 0 };

        return (
            <tr className={this._props.rowStyle} onPointerEnter={action(() => (this.isPointerOver = true))} onPointerLeave={action(() => (this.isPointerOver = false))}>
                <td className="keyValuePair-td-key" style={{ width: `${this._props.keyWidth}%` }}>
                    <div className="keyValuePair-td-key-container">
                        <button
                            style={hover}
                            className="keyValuePair-td-key-delete"
                            onClick={undoBatch(() => {
                                if (Object.keys(props.Document).indexOf(props.fieldKey) !== -1) {
                                    delete props.Document[props.fieldKey];
                                } else delete DocCast(props.Document.proto)?.[props.fieldKey];
                            })}>
                            X
                        </button>
                        <input className="keyValuePair-td-key-check" type="checkbox" style={hover} onChange={this.handleCheck} ref={this.checkbox} />
                        <Tooltip title={Object.entries(new DocumentOptions()).find((pair: [string, FInfo]) => pair[0].replace(/^_/, '') === props.fieldKey)?.[1].description ?? ''}>
                            <div className="keyValuePair-keyField" style={{ marginLeft: 20 * (props.fieldKey.match(/_/g)?.length || 0), color: keyStyle }}>
                                {'('.repeat(parenCount)}
                                {props.fieldKey}
                                {')'.repeat(parenCount)}
                            </div>
                        </Tooltip>
                    </div>
                </td>
                <td className="keyValuePair-td-value" style={{ width: `${100 - this._props.keyWidth}%` }} onContextMenu={this.onContextMenu}>
                    <div className="keyValuePair-td-value-container">
                        <EditableView contents={undefined} fieldContents={props} GetValue={() => Field.toKeyValueString(props.Document, props.fieldKey)} SetValue={(value: string) => KeyValueBox.SetField(props.Document, props.fieldKey, value)} />
                    </div>
                </td>
            </tr>
        );
    }
}
