/* eslint-disable react/no-unused-prop-types */
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, computed, makeObservable, 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';
import { IconButton, Size } from 'browndash-components';

export enum SchemaFieldType {
    Header, Cell
}

export interface SchemaColumnHeaderProps {
    Document: Doc;
    autoFocus?: boolean;
    columnKeys: string[];
    columnWidths: number[];
    columnIndex: number;
    schemaView: CollectionSchemaView;
    keysDropdown: React.JSX.Element;
    //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;
    @observable _showMenuIcon: boolean = false;

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

    constructor(props: SchemaColumnHeaderProps){
        super(props);
        makeObservable(this);
        this._props.schemaView.openColumnMenu(0, false)
    }
    
    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 updateKeyDropdown = (value: string) => {this._props.schemaView.updateKeySearch(value)}

    openKeyDropdown = () => {
        this._props.schemaView.openColumnMenu(this._props.columnIndex, 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' onPointerUp={() => {SchemaColumnHeader.isDefaultField(this.fieldKey) && this.openKeyDropdown()}}
        style={{
            color,
            width: '100%',
            pointerEvents,
        }}>
            <EditableView
                ref={r => this._props.autoFocus && r?.setIsFocused(true)}
                oneLine={true}
                allowCRs={false}
                contents={undefined}
                onClick={this.openKeyDropdown}
                fieldContents={fieldProps}
                editing={undefined}  
                placeholder={'Add key'}
                updateAlt={this.updateAlt} // alternate title to display
                updateSearch={this.updateKeyDropdown}
                schemaFieldType={SchemaFieldType.Header} 
                GetValue={() => {
                    if (SchemaColumnHeader.isDefaultField(this.fieldKey)) return '';
                    else if (this._altTitle) return this._altTitle;
                    else return this.fieldKey;
                }}
                SetValue={undoable((value: string, shiftKey?: boolean, enterKey?: boolean) => {
                    if (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>
    }

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

    get headerButton(){
        const toRender = SchemaColumnHeader.isDefaultField(this.fieldKey) ? 
        (<IconButton
            icon={ <FontAwesomeIcon icon="trash" size='sm'/>}
            size={Size.XSMALL}
            color={'black'}
            onPointerDown={e =>
                setupMoveUpEvents(
                    this,
                    e,
                    returnFalse,
                    emptyFunction,
                    undoable(clickEv => {
                        clickEv.stopPropagation();
                        this._props.schemaView.removeColumn(this._props.columnIndex);
                    }, 'open column menu')
                )
            }
        />)
        : (<IconButton
            icon={ <FontAwesomeIcon icon="caret-down" size='lg'/>}
            size={Size.XSMALL}
            color={'black'}
            onPointerDown={e =>
                setupMoveUpEvents(
                    this,
                    e,
                    returnFalse,
                    emptyFunction,
                    undoable(clickEv => {
                        clickEv.stopPropagation();
                        this._props.openContextMenu(e.clientX, e.clientY, this._props.columnIndex)
                    }, 'open column menu')
                )
            }
        />)

        return toRender;
    }

    @action handlePointerEnter = () => this._showMenuIcon = true;
    @action handlePointerLeave = () => this._showMenuIcon = false;

    @computed get displayButton() {return this._showMenuIcon;}

    render() {
        return (
                <div
                    className="schema-column-header"
                    style={{
                        width: this._props.columnWidths[this._props.columnIndex],
                    }}
                    onPointerEnter={() => {this.handlePointerEnter()}}
                    onPointerLeave={() => {this.handlePointerLeave()}}
                    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">
                            {this.displayButton ? this.headerButton : null}
                        </div>
                    </div>  
                </div>
        );
    }
}
