import { FC } from 'react';
import { useFormContext } from 'react-hook-form';

import HuCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox';

import { addOrRemove } from 'src/utils/arrays';

import { SegmentationDataMapped } from './SegmentationsData';

type Props = {
  segmentation: SegmentationDataMapped;
  item: {
    id: number;
    name: string;
    groupId: number;
  };
};

export const SegmentationItemCheckbox: FC<Props> = ({ segmentation, item }) => {
  const { setValue, watch } = useFormContext();

  const segmentationItemIds = watch('segmentationItemIds');
  const segmentationDefined = segmentationItemIds[segmentation.id];

  const onHandleChangeItem = () => {
    const newItems = segmentationDefined
      ? addOrRemove(segmentationDefined, item.id)
      : [item.id];

    setValue('segmentationItemIds', {
      ...segmentationItemIds,
      [segmentation.id]: newItems,
    });
  };

  const isChecked = () => {
    return segmentationDefined && segmentationDefined.includes(item.id);
  };

  return (
    <HuCheckbox
      checked={isChecked() || false}
      label={item.name}
      onChange={onHandleChangeItem}
    />
  );
};
