import { ComponentType } from 'react';

import { FieldState } from 'formstate';

import { TableCell } from '@servicetitan/design-system';
import { TableCellProps } from '../table';
import { PossibleFormState } from '../table-state';

export interface EditorProps<T, TRow = unknown> extends TableCellProps<any> {
    fieldState: FieldState<T>;
    formState: PossibleFormState<TRow>;
}

interface GetEditableCellParams<T> {
    viewer?: ComponentType<TableCellProps<any>>;
    editor: ComponentType<EditorProps<T>>;
}

export function getEditableCell<T>({
    viewer: Viewer = TableCell,
    editor: Editor,
}: GetEditableCellParams<T>) {
    return (props: TableCellProps<any>) => {
        const { tableState, field, dataItem, rowType } = props;

        if (rowType !== 'data') {
            return <TableCell {...props} />;
        }

        const editingForm =
            tableState?.dataSource?.idSelector &&
            tableState.inEdit.get(tableState.dataSource.idSelector(dataItem));

        if (field && editingForm && (!editingForm.field || editingForm.field === field)) {
            return (
                <Editor
                    {...props}
                    formState={editingForm.form}
                    fieldState={editingForm.form.$[field]}
                />
            );
        }

        return <Viewer {...props} />;
    };
}
