import { makeObservable, action, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Docs } from '../../documents/Documents';
import { DocumentType } from '../../documents/DocumentTypes';
import { FieldView } from './FieldView';

import { DateField } from '../../../fields/DateField';
import { Doc, FieldType } from '../../../fields/Doc';

interface TaskManagerProps {
    Document: Doc;
}
  
@observer
export class TaskManagerTask extends React.Component<TaskManagerProps> {
public static LayoutString(fieldStr: string) {
    return FieldView.LayoutString(TaskManagerTask, fieldStr);
}

@action
updateText = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.props.Document.text = e.target.value;
};

@action
updateAllDay = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.props.Document.allDay = e.target.checked;
};

@action
updateStart = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.props.Document.startTime = new DateField(new Date(e.target.value));
};

@action
updateEnd = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.props.Document.endTime = new DateField(new Date(e.target.value));
};

render() {
    const doc = this.props.Document;

    const taskDesc = typeof doc.text === 'string' ? doc.text : '';
    const allDay = !!doc.allDay;

    const startTime = doc.startTime instanceof DateField ? doc.startTime.date.toISOString().slice(0, 16) : '';

    const endTime = doc.endTime instanceof DateField ? doc.endTime.date.toISOString().slice(0, 16) : '';

    return (
    <div style={{ padding: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <input
        type="text"
        placeholder="What’s your task?"
        value={taskDesc}
        onChange={this.updateText}
        />

        <label>
        <input type="checkbox" checked={allDay} onChange={this.updateAllDay} />
        All day
        </label>

        {!allDay && (
        <div style={{ display: 'flex', gap: 8 }}>
            <label>
            Start:
            <input type="datetime-local" value={startTime} onChange={this.updateStart} />
            </label>
            <label>
            End:
            <input type="datetime-local" value={endTime} onChange={this.updateEnd} />
            </label>
        </div>
        )}
    </div>
    );
}
}

Docs.Prototypes.TemplateMap.set(DocumentType.TASK, {
    layout: { view: TaskManagerTask, dataField: 'text' },
    options: {
        acl: '',
        _height: 35,
        _xMargin: 10,
        _yMargin: 10,
        _layout_autoHeight: true,
        _layout_nativeDimEditable: true,
        _layout_reflowVertical: true,
        _layout_reflowHorizontal: true,
        defaultDoubleClick: 'ignore',
        systemIcon: 'BsCheckSquare', // or whatever icon you like
    },
});
