/* eslint-disable react/no-unused-prop-types */
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, computed, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { returnEmptyDoclist, returnEmptyFilter, returnFalse, returnZero, setupMoveUpEvents } from '../../../../ClientUtils';
import { emptyFunction } from '../../../../Utils';
import { Colors } from '../../global/globalEnums';
import './CollectionSchemaView.scss';
import { EditableView } from '../../EditableView';
import { DefaultStyleProvider, returnEmptyDocViewList } from '../../StyleProvider';
import { FieldViewProps } from '../../nodes/FieldView';
import { Doc, Field } from '../../../../fields/Doc';
import { dropActionType } from '../../../util/DropActionTypes';
import { Transform } from 'prosemirror-transform';
import { SchemaTableCell } from './SchemaTableCell';
import { DocCast } from '../../../../fields/Types';
import { computedFn } from 'mobx-utils';
import { CollectionSchemaView } from './CollectionSchemaView';
import { SnappingManager } from '../../../util/SnappingManager';
import { undoable } from '../../../util/UndoManager';
import { FInfo } from '../../../documents/Documents';

export interface SchemaColumnHeaderProps {
    Document: Doc;
    autoFocus?: boolean;
    oneLine?: boolean; // whether all input should fit on one line vs allowing textare multiline inputs
    allowCRs?: boolean; // allow carriage returns in text input (othewrise CR ends the edit)
    columnKeys: string[];
    columnWidths: number[];
    columnIndex: number;
    sortField: string;
    sortDesc: boolean;
    schemaView: CollectionSchemaView;
    //cleanupField: (s: string) => string;
    isContentActive: (outsideReaction?: boolean | undefined) => boolean | undefined;
    setSort: (field: string | undefined, desc?: boolean) => void;
    removeColumn: (index: number) => void;
    rowHeight: () => number;
    resizeColumn: (e: any, index: number) => void;
    dragColumn: (e: any, index: number) => boolean;
    openContextMenu: (x: number, y: number, index: number) => void;
    setColRef: (index: number, ref: HTMLDivElement) => void;
    rootSelected?: () => boolean;
    columnWidth: () => number;
    finishEdit?: () => void; // notify container that edit is over (eg. to hide view in DashFieldView)
    //transform: () => Transform;
}

@observer
export class SchemaColumnHeader extends React.Component<SchemaColumnHeaderProps> {

    @observable _editing: boolean = false;

    get fieldKey() {
        return this.props.columnKeys[this.props.columnIndex];
    }

    // getFinfo = computedFn((fieldKey: string) => this.props.schemaView?.fieldInfos.get(fieldKey));
    // setColumnValues = (field: string, value: string) => this.props.schemaView?.setColumnValues(field, value);

    @action
    sortClicked = (e: React.PointerEvent) => {
        e.stopPropagation();
        e.preventDefault();
        if (this.props.sortField === this.fieldKey && this.props.sortDesc) {
            this.props.setSort(undefined);
        } else if (this.props.sortField === this.fieldKey) {
            this.props.setSort(this.fieldKey, true);
        } else {
            this.props.setSort(this.fieldKey, false);
        }
    };

    @action
    setupDrag = (e: React.PointerEvent) => {
        this.props.isContentActive(true) && setupMoveUpEvents(this, e, moveEv => this.props.dragColumn(moveEv, this.props.columnIndex), emptyFunction, emptyFunction);
    };

    // public static renderProps(props: SchemaColumnHeaderProps) {
    //     const { columnKeys, columnWidth, isContentActive, Document } = props;
    //     const fieldKey = columnKeys[props.columnIndex];
    //     const color = 'black'; // color of text in cells
    //     const fieldProps: FieldViewProps = {
    //         childFilters: returnEmptyFilter,
    //         childFiltersByRanges: returnEmptyFilter,
    //         docViewPath: returnEmptyDocViewList,
    //         searchFilterDocs: returnEmptyDoclist,
    //         styleProvider: DefaultStyleProvider,
    //         isSelected: returnFalse,
    //         setHeight: returnFalse,
    //         select: emptyFunction,
    //         dragAction: dropActionType.move,
    //         renderDepth: 1,
    //         noSidebar: true,
    //         isContentActive: returnFalse,
    //         whenChildContentsActiveChanged: emptyFunction,
    //         ScreenToLocalTransform: Transform.Identity,
    //         focus: emptyFunction,
    //         addDocTab: SchemaTableCell.addFieldDoc,
    //         pinToPres: returnZero,
    //         Document: DocCast(Document.rootDocument, Document),
    //         fieldKey: fieldKey,
    //         PanelWidth: columnWidth,
    //         PanelHeight: props.rowHeight,
    //         rootSelected: props.rootSelected,
    //     };
    //     const readOnly = getFinfo(fieldKey)?.readOnly ?? false;
    //     const cursor = !readOnly ? 'text' : 'default';
    //     const pointerEvents = 'all';
    //     return { color, fieldProps, cursor, pointerEvents };
    // }

    // @computed get editableView() {
    //     const { color, fieldProps, pointerEvents } = SchemaColumnHeader.renderProps(this.props); 

    //     return <EditableView
    //             ref={r => this.props.autoFocus && r?.setIsFocused(true)}
    //             oneLine={this.props.oneLine}
    //             allowCRs={this.props.allowCRs}
    //             contents={undefined}
    //             fieldContents={fieldProps}
    //             editing={this._editing ? undefined : false}
    //             GetValue={() => this.props.cleanupField(Field.toKeyValueString(fieldProps.Document, this.fieldKey, SnappingManager.MetaKey)).replace(/[";]/g, '')} //TODO: feed this into parser that handles idToDoc
    //             SetValue={undoable((value: string, enterKey?: boolean) => {
    //                 if (enterKey) this.setColumnValues(this.fieldKey.replace(/^_/, ''), value);
    //                 this.props.finishEdit?.();
    //                 return true;
    //             }, 'edit schema cell')}
    //         />
    // }

    render() {
        return (
            <div
                className="schema-column-header"
                style={{
                    width: this.props.columnWidths[this.props.columnIndex],
                }}
                onPointerDown={this.setupDrag}
                ref={col => {
                    if (col) {
                        this.props.setColRef(this.props.columnIndex, col);
                    }
                }}>
                <div className="schema-column-resizer left" onPointerDown={e => this.props.resizeColumn(e, this.props.columnIndex)} />
                <div className="schema-column-title" onPointerDown={e => {this._editing = true; console.log(this._editing)}}>{this.fieldKey}</div>

                <div className="schema-header-menu">
                    <div className="schema-header-button" onPointerDown={e => this.props.openContextMenu(e.clientX, e.clientY, this.props.columnIndex)}>
                        <FontAwesomeIcon icon="ellipsis-h" />
                    </div>
                    <div className="schema-sort-button" onPointerDown={this.sortClicked} style={this.props.sortField === this.fieldKey ? { backgroundColor: Colors.MEDIUM_BLUE } : {}}>
                        <FontAwesomeIcon icon="caret-right" style={this.props.sortField === this.fieldKey ? { transform: `rotate(${this.props.sortDesc ? '270deg' : '90deg'})` } : {}} />
                    </div>
                </div>
            </div>
        );
    }
}
