import { ComponentType, FC } from 'react';

import { observer } from 'mobx-react';

import { DropDownList, DropDownListChangeEvent } from '@progress/kendo-react-dropdowns';

import { TableCellProps } from '../table';
import { getEditableCell, EditorProps } from './get-editable-cell';

import { Option } from '@servicetitan/form';

import classNames from 'classnames';

interface GetSelectEditableCellParams<T> {
    options: Option<T>[];
    viewer?: ComponentType<TableCellProps<any>>;
}

export function getSelectEditableCell<T>({ options, viewer }: GetSelectEditableCellParams<T>) {
    const Editor = observer<FC<EditorProps<T>>>(
        ({ fieldState: { value, onChange, hasError, error }, className, tdProps }) => {
            const selected = options.find(option => option.value === value);

            const handleChange = (event: DropDownListChangeEvent) => {
                onChange(event.target.value.value);
            };

            return (
                <td className={classNames('of-visible', className)} {...tdProps}>
                    <DropDownList
                        data={options}
                        value={selected}
                        onChange={handleChange}
                        dataItemKey="value"
                        textField="text"
                        valid={!hasError}
                        validationMessage={error}
                        className="w-100"
                    />
                </td>
            );
        }
    );

    return getEditableCell({
        viewer,
        editor: Editor,
    });
}
