import { useEffect, FC } from 'react';

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

import { observer } from 'mobx-react';

import { Icon, Checkbox, CheckboxProps } from '@servicetitan/design-system';

import { Table, TableColumn, TableDetailRowProps } from '../..';

import { DetailTableStore } from './detail-table.store';

export const DetailTable: FC<TableDetailRowProps> = provide({
    singletons: [DetailTableStore],
})(
    observer(({ dataItem }) => {
        const [store] = useDependencies(DetailTableStore);

        useEffect(() => {
            store.initialize(dataItem);
            return () => store.dispose();
        }, [store, dataItem]);

        if (!store.tableState) {
            return null;
        }

        return (
            <Table
                selectable
                hideSelectAll
                tableState={store.tableState}
                selectionControl={LockFieldIcon}
            >
                <TableColumn field="Field" />

                <TableColumn field="OldValue" />

                <TableColumn field="NewValue" />
            </Table>
        );
    })
);

const LockFieldIcon: FC<CheckboxProps<never>> = props => {
    const { checked, disabled } = props;

    if (!disabled) {
        return <Checkbox {...props} />;
    }

    return (
        <div>
            {checked ? (
                <Icon name="check" className="c-blue-300" />
            ) : (
                <Icon name="remove" className="c-neutral-70" />
            )}
        </div>
    );
};
