import CustomLabel from '@design-system/Inputs/Base/CustomLabel';
import RadioButton from '@design-system/RadioButton/RadioButton';
import { FormControl, RadioGroup, type SxProps } from '@mui/material';

import { type RadioInputOption, type RadioInputProps } from './types';

const RadioInput = ({
  name,
  options,
  value,
  onChange,
  label,
  error = false,
  success = false,
  disabled = false,
  slotProps = {},
  sx = {},
}: RadioInputProps) => {
  const handleChange = (option: RadioInputOption) => () => {
    if (!option.disabled && onChange) {
      onChange(option.value);
    }
  };

  return (
    <FormControl
      error={error}
      disabled={disabled}
      fullWidth
      {...slotProps.root}
      sx={
        {
          gap: 2,
          ...sx,
          ...slotProps.root?.sx,
        } as SxProps
      }
    >
      {label && (
        <CustomLabel
          id={`${name}-label`}
          label={label}
          success={success}
          {...slotProps.label}
        />
      )}
      <RadioGroup
        name={name}
        aria-labelledby={`${name}-label`}
        {...slotProps.radioGroup}
        sx={
          {
            gap: 2,
            ...slotProps.radioGroup?.sx,
          } as SxProps
        }
      >
        {options.map(option => (
          <RadioButton
            key={option.value}
            label={option.label}
            description={option.description}
            isActive={value === option.value}
            disabled={disabled || option.disabled}
            error={error}
            value={option.value}
            onClick={handleChange(option)}
            {...slotProps.radioButton}
          />
        ))}
      </RadioGroup>
    </FormControl>
  );
};

export default RadioInput;
