/* 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 { ObservableReactComponent } from '../../ObservableReactComponent';
import { DefaultStyleProvider, returnEmptyDocViewList } from '../../StyleProvider';
import { FieldViewProps } from '../../nodes/FieldView';
import { Doc, Field } from '../../../../fields/Doc';
import { dropActionType } from '../../../util/DropActionTypes';
import { Transform } from '../../../util/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';
import { ColumnType } from '../../../../fields/SchemaHeaderField';

export interface SchemaColumnHeaderProps {
    Document: Doc;
    autoFocus?: boolean;
    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 ObservableReactComponent<SchemaColumnHeaderProps> {

    @observable _altTitle: string | undefined = undefined;

    @computed get fieldKey() {
        return this._props.columnKeys[this._props.columnIndex];
    }

    isDefaultTitle = (key: string) => {
        const defaultPattern = /EmptyColumnKey/;
        let isDefault: boolean = (defaultPattern.exec(key) != null);
        return isDefault;
    }

    getFinfo = computedFn((fieldKey: string) => this._props.schemaView?.fieldInfos.get(fieldKey));
    setColumnValues = (field: string, defaultValue: string) => {this._props.schemaView?.setKey(field, defaultValue, this._props.columnIndex);}
    @action updateAlt = (newAlt: string) => {this._altTitle = newAlt;}

    @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);
    };

    renderProps = (props: SchemaColumnHeaderProps) => {
        const { columnKeys, columnWidth, 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 = this.getFinfo(fieldKey)?.readOnly ?? false;
        const cursor = !readOnly ? 'text' : 'default';
        const pointerEvents: 'all' | 'none' = 'all';
        return { color, fieldProps, cursor, pointerEvents };
    }

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

        return <div className='schema-column-edit-wrapper' 
        style={{
            color,
            width: '100%',
            pointerEvents,
        }}>
            <EditableView
                ref={r => this._props.autoFocus && r?.setIsFocused(true)}
                oneLine={true}
                allowCRs={false}
                contents={undefined}
                fieldContents={fieldProps}
                editing={undefined}  
                updateAlt={this.updateAlt} // alternate title to display
                showKeyNotVal={true} // tells the EditableView to display the fieldKey itself, and not its value
                GetValue={() => {
                    if (this.isDefaultTitle(this.fieldKey)) return '';
                    else if (this._altTitle) return this._altTitle;
                    else return this.fieldKey;
                }}
                SetValue={undoable((value: string, shiftKey?: boolean, enterKey?: boolean) => {
                    if (shiftKey && enterKey) { // if shift & enter, set value of each cell in column
                        this.setColumnValues(value, '');
                        this._altTitle = undefined;
                        this._props.finishEdit?.();
                        return true;
                    } else if (enterKey) this.updateAlt(value);
                    this._props.finishEdit?.(); 
                    return true;
                }, 'edit column header')}
            />
            </div>
    }

    // staticView = () => {
    //      return <div className="schema-column-title" onPointerDown={e => {this._editing = true; console.log(this._editing)}}>{this.fieldKey}</div>
    // }

    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>{this.editableView}</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>
        );
    }
}
