import { forwardRef } from 'react';

import { RadioGroup as MUIRadioGroup, Stack } from '@mui/material';

import RadioButton from '../../design-system/RadioButton/RadioButton';
import SelectionCard from '../SelectionCard';

import { type RadioGroupProps } from './types';

export const RadioGroup = forwardRef<HTMLDivElement, RadioGroupProps>(
  ({ options, value, onChange, error = false, slotProps = {} }, ref) => {
    return (
      <MUIRadioGroup
        ref={ref}
        sx={{ display: 'contents' }}
      >
        <Stack
          {...slotProps.root}
          sx={{
            gap: 2,
            ...slotProps.root?.sx,
          }}
        >
          {options.map(option => (
            <SelectionCard
              key={option.value}
              {...slotProps.selectionCard}
              checked={value === option.value}
              onClick={() => {
                if (!option.disabled && onChange) {
                  onChange(option.value);
                }
              }}
              fullWidth={slotProps.selectionCard?.fullWidth ?? true}
              sx={{
                opacity: option.disabled ? 0.6 : 1,
                ...slotProps.selectionCard?.sx,
              }}
            >
              <RadioButton
                {...slotProps.radioButton}
                label={option.label}
                description={option.helperText}
                isActive={value === option.value}
                disabled={option.disabled}
                error={error}
                value={option.value}
              />
            </SelectionCard>
          ))}
        </Stack>
      </MUIRadioGroup>
    );
  },
);

RadioGroup.displayName = 'RadioGroup';

export default RadioGroup;
