import { Button } from '@servicetitan/design-system';
import { FC, SyntheticEvent, useCallback, useMemo } from 'react';
import { TableCellProps, TableColumn } from '../index';

export const RowExpandCell: FC<TableCellProps> = ({
    dataItem,
    dataIndex,
    expanded,
    tableState,
    className,
    tdProps,
}) => {
    const onCLick = useCallback(
        (e: SyntheticEvent) => {
            tableState?.handleExpandChange({
                dataItem,
                dataIndex,
                value: !expanded,
                syntheticEvent: e,
                nativeEvent: e.nativeEvent,
                target: e.target as never,
            });
        },
        [dataItem, dataIndex, expanded, tableState]
    );

    return (
        <td className={className} {...tdProps}>
            <Button
                iconName={expanded ? 'expand_less' : 'expand_more'}
                aria-label="expand row"
                size="xsmall"
                fill="subtle"
                onClick={onCLick}
            />
        </td>
    );
};

export const getRowExpandColumn = () => (
    <TableColumn
        field="expanded"
        title=" "
        editable={false}
        sortable={false}
        resizable={false}
        cell={RowExpandCell}
        width="50px"
    />
);

export const useRowExpandColumn = () => {
    return useMemo(getRowExpandColumn, []);
};
