import { type FC } from 'react';
import { Controller, useFormContext } from 'react-hook-form';

import { RadioGroup } from '@mui/material';

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

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

const FormRadioButtonGroup: FC<FormRadioButtonGroupProps> = props => {
  const { name, options, radioProps, rules, disabled, ...other } = props;

  const { control, setValue, watch } = useFormContext();
  const groupName = watch(name);

  return (
    <Controller
      name={name}
      control={control}
      rules={rules}
      render={({ field: { onChange, ...field } }) => (
        <RadioGroup
          {...field}
          {...other}
        >
          {options.map(option => (
            <CardContainer
              key={option.value}
              sx={{ width: '100%', cursor: 'pointer' }}
              onClick={() => {
                // Prevent triggering selection when user is selecting text
                if (
                  window.getSelection()?.type !== 'Range' &&
                  !option.disabled
                ) {
                  setValue(name, option.value, { shouldDirty: true });
                }
              }}
            >
              <RadioButton
                {...radioProps}
                label={option.label}
                onClick={() => {
                  setValue(name, option.value, { shouldDirty: true });
                }}
                description={option.helperText}
                value={option.value}
                isActive={groupName === option.value}
                disabled={option.disabled}
              />
            </CardContainer>
          ))}
        </RadioGroup>
      )}
    />
  );
};

export default FormRadioButtonGroup;
