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

import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

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

import { toggleIndex } from './utils';

type ReviewPerformanceMultipleChoiceCardsProps = {
  name: string;
  choiceLabels: string[];
  required?: boolean;
  disabled?: boolean;
  defaultValue?: number[];
};

const ReviewPerformanceMultipleChoiceCards = ({
  name,
  choiceLabels,
  required,
  disabled,
  defaultValue,
}: ReviewPerformanceMultipleChoiceCardsProps) => {
  const { control } = useFormContext();
  const theme = useTheme();

  return (
    <Controller
      control={control}
      name={name}
      defaultValue={defaultValue}
      rules={{
        validate: (v: number[] | undefined) => {
          if (!required || disabled) return true;
          return !!(Array.isArray(v) && v.length > 0);
        },
      }}
      render={({ field: { onChange, value } }) => (
        <Stack sx={{ gap: 2, width: '100%' }}>
          {choiceLabels.map((label, index) => {
            const list = (value as number[] | undefined) ?? [];
            const checked = list.includes(index);
            return (
              <HuCardContainer
                key={`${name}-${String(index)}`}
                fullWidth
                noHover={disabled}
                onClick={
                  disabled
                    ? undefined
                    : () =>
                        onChange(
                          toggleIndex(value as number[] | undefined, index),
                        )
                }
                sx={{
                  cursor: disabled ? 'default' : 'pointer',
                  borderColor: checked
                    ? theme.palette.new.action.button.background.primary.default
                    : theme.palette.new.border.neutral.default,
                  backgroundColor: checked
                    ? theme.palette.new.background.layout.brand
                    : theme.palette.new.background.elements.default,
                }}
              >
                <Stack
                  sx={{
                    pointerEvents: disabled ? 'auto' : 'none',
                    width: '100%',
                  }}
                >
                  <HuCheckbox
                    label={label}
                    checked={checked}
                    disabled={disabled}
                  />
                </Stack>
              </HuCardContainer>
            );
          })}
        </Stack>
      )}
    />
  );
};

export default ReviewPerformanceMultipleChoiceCards;
