import { ComponentType } from 'react';

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

import { PossibleFormState } from '../table-state';

export interface EditActionProps<T> extends TableCellProps<T> {
    formState: PossibleFormState<T>;
}

interface GetActionCellParams<T> {
    view: ComponentType<TableCellProps<T>>;
    edit: ComponentType<EditActionProps<T>>;
}

export function getActionCell<T>({ view: ViewAction, edit: EditAction }: GetActionCellParams<T>) {
    return (props: TableCellProps<T>) => {
        const { tableState, dataItem, rowType } = props;

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

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

        if (editingForm) {
            return <EditAction {...props} formState={editingForm.form} />;
        }

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