import { type FieldValues, type UseControllerReturn } from 'react-hook-form';

import SelectionCard from '@composed-components/SelectionCard';
import Checkbox, { type CheckboxProps } from '@design-system/Checkbox/Checkbox';
import RadioButton, {
  type RadioButtonProps,
} from '@design-system/RadioButton/RadioButton';

export type SelectableListItemOption = {
  id: number;
  label: string;
  value: string;
};

type InputSelectableListItemProps = {
  option: SelectableListItemOption;
  isMultipleSelect: boolean;
  controller: UseControllerReturn<FieldValues, string>;
  fieldProps?: RadioButtonProps | CheckboxProps;
  disabled?: boolean;
};

const InputSelectableListItem = ({
  option,
  isMultipleSelect,
  controller,
  disabled,
  fieldProps,
}: InputSelectableListItemProps) => {
  const fieldValue = controller.field.value ?? (isMultipleSelect ? [] : null);

  const isSelected = isMultipleSelect
    ? (fieldValue as number[])?.some(id => id === option.id) || false
    : (fieldValue as number) === option.id;

  const handleClickOption = (selectedOption: SelectableListItemOption) => {
    if (disabled) return;

    if (!isMultipleSelect) controller.field.onChange(selectedOption.id);
    else {
      const currentValues = (fieldValue as number[]) || [];
      const isSelectedOption = currentValues.some(
        id => id === selectedOption.id,
      );
      const newValues = isSelectedOption
        ? currentValues.filter(id => id !== selectedOption.id)
        : [...currentValues, selectedOption.id];
      controller.field.onChange(newValues);
    }
  };

  // We do this because if the card is disabled there is no contrast and the selected option is not visible.
  const isCardDisabled = disabled && !isSelected;

  return (
    <SelectionCard
      key={option.id}
      sx={{ width: '100%' }}
      checked={isSelected}
      disabled={isCardDisabled}
      aria-disabled={isCardDisabled}
      onClick={() => handleClickOption(option)}
    >
      <span style={{ pointerEvents: 'none' }}>
        {isMultipleSelect ? (
          <Checkbox
            checked={isSelected}
            disabled={disabled}
            label={option.label}
            {...(fieldProps as CheckboxProps)}
          />
        ) : (
          <RadioButton
            checked={isSelected}
            isActive={isSelected}
            disabled={disabled}
            {...(fieldProps as RadioButtonProps)}
            label={option.label}
          />
        )}
      </span>
    </SelectionCard>
  );
};

export default InputSelectableListItem;
