import { Controller, useFormContext } from 'react-hook-form';

import Card from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';
import CardHeader from '@material-hu/mui/CardHeader';
import Checkbox from '@material-hu/mui/Checkbox';
import Divider from '@material-hu/mui/Divider';
import FormControlLabel from '@material-hu/mui/FormControlLabel';
import Grid from '@material-hu/mui/Grid';

import useSegmentationGroups from 'src/hooks/queryHooks/useSegmentationGroups';
import { addOrRemove, addOrRemoveFullObjBy } from 'src/utils/arrayUtils';

import CircularProgress from 'src/components/CircularProgress';

import { FieldValues } from '../../form';

const SegmentationTab = () => {
  const { data: segmentationGroups, isLoading } = useSegmentationGroups();

  const { watch, setValue } = useFormContext<FieldValues>();
  const { segmentation, segmentationForLog } = watch();

  const handleChange = segmentationItem => {
    const newSegmentation = addOrRemove(segmentation, segmentationItem.id);
    const newSegmentationForLog = addOrRemoveFullObjBy(
      segmentationForLog,
      'id',
      {
        segmentationId: segmentationItem?.groupId,
        id: segmentationItem?.id,
        name: segmentationItem?.name,
      },
    );
    setValue('segmentation', newSegmentation, { shouldDirty: true });
    setValue('segmentationForLog', newSegmentationForLog, {
      shouldDirty: true,
    });
  };

  return isLoading ? (
    <CircularProgress centered />
  ) : (
    <Grid
      container
      columns={3}
      spacing={2}
    >
      {segmentationGroups?.map(segmentationGroup => (
        <Grid
          item
          xs={3}
          sm={1}
          key={segmentationGroup.name}
        >
          <Card>
            <CardHeader title={segmentationGroup.name} />
            <Divider />
            <Controller
              name="segmentation"
              render={() => (
                <CardContent
                  sx={{
                    maxHeight: 300,
                    overflowY: 'auto',
                  }}
                >
                  {segmentationGroup.items.map(segmentationItem => (
                    <FormControlLabel
                      control={
                        <Checkbox
                          name={segmentationItem.name}
                          checked={segmentation.includes(segmentationItem.id)}
                          onChange={() => handleChange(segmentationItem)}
                        />
                      }
                      label={segmentationItem.name}
                      sx={{ display: 'block' }}
                      key={segmentationItem.id}
                    />
                  ))}
                </CardContent>
              )}
            />
          </Card>
        </Grid>
      ))}
    </Grid>
  );
};

export default SegmentationTab;
