import { Component, Fragment } from 'react';

import { observer } from 'mobx-react';
import { observable, action, makeObservable } from 'mobx';

import { DropDownList, DropDownListChangeEvent } from '@progress/kendo-react-dropdowns';
import {
    DatePicker,
    DatePickerChangeEvent,
    TimePicker,
    TimePickerChangeEvent,
} from '@progress/kendo-react-dateinputs';

import {
    IsUnaryFilter,
    cellOperatorChange,
} from '@progress/kendo-react-grid/dist/npm/filterCommon';

import type { TableFilterCellProps } from '@servicetitan/design-system';

import { renderCustomColumnMenuFilter } from '../column-menu-filters';

@observer
class DateTimeFilterCell extends Component<TableFilterCellProps> {
    @observable operator =
        this.props.operators.find(o => o.operator === this.props.operator) ??
        this.props.operators[0];

    constructor(props: TableFilterCellProps) {
        super(props);
        makeObservable(this);
    }

    @action
    handleOperatorChange = (event: DropDownListChangeEvent) => {
        this.operator = event.target.value;
        cellOperatorChange(event, this.props.value, this.props.onChange);
    };

    handleChange = (event: DatePickerChangeEvent | TimePickerChangeEvent) => {
        const value = event.value;

        this.props.onChange({
            value,
            operator: this.props.operator ?? '',
            syntheticEvent: event.syntheticEvent,
        });
    };

    render() {
        return (
            <Fragment>
                <DropDownList
                    value={this.operator}
                    onChange={this.handleOperatorChange}
                    data={this.props.operators}
                    dataItemKey="operator"
                    className="m-b-1"
                    textField="text"
                />
                {!IsUnaryFilter(this.operator.operator) && (
                    <Fragment>
                        <DatePicker
                            value={this.props.value}
                            onChange={this.handleChange}
                            className="m-b-1"
                        />
                        <TimePicker
                            value={this.props.value}
                            onChange={this.handleChange}
                            className="m-b-1"
                        />
                    </Fragment>
                )}
            </Fragment>
        );
    }
}

export const DateTimeColumnMenuFilter = renderCustomColumnMenuFilter(DateTimeFilterCell, true);
