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 HuRadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';

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

const ReviewPerformanceSingleChoiceCards = ({
  name,
  choices,
  required,
  disabled,
  defaultValue,
}: ReviewPerformanceSingleChoiceCardsProps) => {
  const { control } = useFormContext();
  const theme = useTheme();

  return (
    <Controller
      control={control}
      name={name}
      defaultValue={defaultValue}
      rules={{ required: required && !disabled }}
      render={({ field: { onChange, value } }) => {
        // Optional questions must be submittable with no answer, so clicking the
        // already-selected option clears the field back to "no answer".
        const toggleChoice = (index: number) =>
          onChange(value === index ? undefined : index);

        return (
          <Stack sx={{ gap: 2, width: '100%' }}>
            {choices.map((label, index) => {
              const selected = value === index;
              return (
                <HuCardContainer
                  key={`${name}-${String(index)}`}
                  fullWidth
                  noHover={disabled}
                  onClick={disabled ? undefined : () => toggleChoice(index)}
                  sx={{
                    cursor: disabled ? 'default' : 'pointer',
                    borderColor: selected
                      ? theme.palette.new.action.button.background.primary
                          .default
                      : theme.palette.new.border.neutral.default,
                    backgroundColor: selected
                      ? theme.palette.new.background.layout.brand
                      : theme.palette.new.background.elements.default,
                  }}
                >
                  <Stack
                    sx={{
                      pointerEvents: disabled ? 'auto' : 'none',
                      width: '100%',
                    }}
                  >
                    <HuRadioButton
                      label={label}
                      isActive={selected}
                      disabled={disabled}
                    />
                  </Stack>
                </HuCardContainer>
              );
            })}
          </Stack>
        );
      }}
    />
  );
};

export default ReviewPerformanceSingleChoiceCards;
