import { FC } from 'react';

import { Button, Icon, Stack } from '@servicetitan/design-system';

import { TableCellProps, getActionCell, EditActionProps } from '../..';

import { Product } from './product';

const ViewAction: FC<TableCellProps<Product>> = ({ tableState, dataItem, tdProps }) => {
    if (!tableState) {
        return <td {...tdProps} />;
    }

    const edit = () => tableState.edit(dataItem);

    return (
        <td {...tdProps}>
            <Button text primary onClick={edit}>
                <Icon name="edit" />
            </Button>
        </td>
    );
};

const EditAction: FC<EditActionProps<Product>> = ({ tableState, formState, dataItem, tdProps }) => {
    if (!tableState) {
        return <td {...tdProps} />;
    }

    const save = async () => {
        const { hasError } = await formState.validate();
        if (hasError) {
            return;
        }

        await tableState.saveEdit(dataItem);
    };

    const cancel = () => tableState.cancelEdit(dataItem);

    return (
        <td {...tdProps}>
            <Stack justifyContent="space-between">
                <Button text onClick={cancel}>
                    <Icon name="do_not_disturb" />
                </Button>

                <Button text primary onClick={save}>
                    <Icon name="done" />
                </Button>
            </Stack>
        </td>
    );
};

export const ActionsCell = getActionCell({
    view: ViewAction,
    edit: EditAction,
});
