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

import HuFormSelectionCard from '@material-hu/components/composed-components/SelectionCard/form';
import HuCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox';

import { useRules } from 'src/hooks/useRules';

import { type EvaluationForm } from '..';

type MultipleChoiceInputProps = {
  choices: string[];
  questionIndex: number;
};

const MultipleChoiceInput = ({
  choices,
  questionIndex,
}: MultipleChoiceInputProps) => {
  const name = `formValues.${questionIndex}` as const;
  const { control, getValues } = useFormContext<EvaluationForm>();

  const values = useWatch({
    control,
    name,
  });

  const valuesForValidation = getValues(name) as boolean[] | undefined;

  const rules = useRules({
    validateAtLeastOneChecked: valuesForValidation ?? [],
  });

  return (
    <>
      {choices.map((choice, choiceIndex) => (
        <HuFormSelectionCard
          key={choice}
          name={`${name}.${choiceIndex}`}
          sx={{
            width: '100%',
            '& button': {
              minHeight: '75px',
            },
          }}
          rules={rules}
        >
          <HuCheckbox
            label={choice}
            checked={Boolean(values?.[choiceIndex])}
          />
        </HuFormSelectionCard>
      ))}
    </>
  );
};

export default MultipleChoiceInput;
