import { useController } from 'react-hook-form';

import { type CheckboxProps } from '@design-system/Checkbox/Checkbox';
import { type RadioButtonProps } from '@design-system/RadioButton/RadioButton';
import FormHelperText from '@mui/material/FormHelperText';
import Stack from '@mui/material/Stack';
import useTheme from '@mui/material/styles/useTheme';
import Typography from '@mui/material/Typography';
import { IconExclamationCircle } from '@tabler/icons-react';

import InputSelectableListItem, {
  type SelectableListItemOption,
} from './InputSelectableListItem';

type InputSelectableListProps = {
  name: string;
  options: SelectableListItemOption[];
  disabled?: boolean;
  isMultipleSelect: boolean;
  fieldProps?: RadioButtonProps | CheckboxProps;
};

const InputSelectableList = ({
  isMultipleSelect,
  options,
  disabled,
  name,
  fieldProps,
}: InputSelectableListProps) => {
  const { palette } = useTheme();
  const controller = useController({ name });
  const { fieldState } = controller;

  return (
    <Stack sx={{ gap: 1 }}>
      {options.map(option => (
        <InputSelectableListItem
          key={option.id}
          option={option}
          controller={controller}
          isMultipleSelect={isMultipleSelect}
          disabled={disabled}
          fieldProps={fieldProps}
        />
      ))}
      <FormHelperText
        sx={{
          mx: 0,
          '& *': { color: `${palette.textColors?.errorText} !important` },
        }}
      >
        <Stack
          component="span"
          sx={{ alignItems: 'center', flexDirection: 'row', gap: 0.5 }}
        >
          {fieldState.error?.message && (
            <>
              {fieldState.error && <IconExclamationCircle size="1rem" />}
              <Typography variant="globalS">
                {fieldState.error?.message}
              </Typography>
            </>
          )}
        </Stack>
      </FormHelperText>
    </Stack>
  );
};

export default InputSelectableList;
