import { FC } from 'react';

import { observer } from 'mobx-react';

import { Input, InputChangeEvent } from '@progress/kendo-react-inputs';

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

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

interface GetTextEditableCellParams<T> {
    placeholder?: string;
    isDisabled?(dataItem: T): boolean;
}

export function getTextEditableCell<T>({
    placeholder,
    isDisabled,
}: GetTextEditableCellParams<T> = {}) {
    const Editor = observer<FC<EditorProps<string>>>(
        ({ fieldState: { value, onChange, hasError, error }, dataItem, className, tdProps }) => {
            const handleChange = (event: InputChangeEvent) => {
                if (typeof event.target.value === 'string') {
                    onChange(event.target.value);
                }
            };

            return (
                <td className={className} {...tdProps}>
                    <Input
                        value={value}
                        onChange={handleChange}
                        valid={!hasError}
                        placeholder={placeholder}
                        disabled={isDisabled?.(dataItem)}
                    />
                    {hasError && <Label label="" hasError error={error} />}
                </td>
            );
        }
    );

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

export const TextEditableCell = getTextEditableCell();
