import { useEffect, FC } from 'react';

import { provide, useDependencies } from '@servicetitan/react-ioc';

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

import { Table, TableColumn, TableCellProps, TableExpandChangeEvent } from '../..';

import { MasterTableStore } from './master-table.store';

import { DetailTable } from './detail-table';

const ExpandCell: FC<TableCellProps> = ({ tableState, dataItem, tdProps }) => {
    const handleExpandChange = () => {
        tableState!.handleExpandChange({
            dataItem,
            value: !dataItem.expanded,
        } as TableExpandChangeEvent);
    };

    return (
        <td {...tdProps}>
            <Button full text primary onClick={handleExpandChange}>
                Show / Hide
            </Button>
        </td>
    );
};

export const TableMasterDetailExample: FC = provide({
    singletons: [MasterTableStore],
})(() => {
    const [store] = useDependencies(MasterTableStore);

    useEffect(() => () => store.dispose());

    return (
        <Table tableState={store.tableState} selectable detail={DetailTable}>
            <TableColumn field="ProductID" title="ID" width="100px" />

            <TableColumn field="ProductName" title="Product Name" />

            <TableColumn cell={ExpandCell} width="150px" />
        </Table>
    );
});
