import React, { FC, useEffect } from 'react';
import { Box } from '../Box';
import { Checkbox } from '../Checkbox';
import { TableCheckboxProps } from './TableTypes';

export const TableCheckbox: FC<TableCheckboxProps> = ({
  onChange,
  setShowBatchActions,
  indeterminate,
  checked,
  ...rest
}) => {
  useEffect(() => {
    if (setShowBatchActions) {
      setShowBatchActions(indeterminate || checked);
    }
  }, [setShowBatchActions, indeterminate, checked]);

  const handleChange = (state: boolean) => {
    const event = { target: { value: state } };
    onChange(event);
  };

  return (
    <Box mt="7px">
      <Checkbox
        onChange={handleChange}
        indeterminate={indeterminate}
        checked={checked}
        {...rest}
      />
    </Box>
  );
};
