import React from 'react';
import {
  Box,
  Typography,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  FormHelperText,
} from '@mui/material';
import { Controller, useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

export interface RadioOption {
  value: string | number;
  label: string;
  disabled?: boolean;
}

export interface RadioFormFieldProps {
  name: string;
  label?: string;
  options: RadioOption[];
  helperText?: string;
  defaultValue?: string | number;
  disabled?: boolean;
  required?: boolean;
  row?: boolean;
  size?: 'small' | 'medium';
  onChangeValue?: (value: string | number) => void;
}

export const RadioFormField: React.FC<RadioFormFieldProps> = ({
  name,
  label,
  options,
  helperText,
  defaultValue = '',
  disabled = false,
  required = false,
  row = true,
  size = 'medium',
  onChangeValue,
}) => {
  const { control } = useFormContext();
  const { t } = useTranslation();

  return (
    <Box>
      <Typography variant="subtitle1" gutterBottom>
        {required && <span style={{ color: 'red' }}>*</span>}
        {label}
      </Typography>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={{
          required: required ? 'This field is required' : false,
        }}
        render={({ field, fieldState: { error } }) => (
          <FormControl component="fieldset" error={!!error}>
            {label && <FormLabel component="legend" sx={{ display: 'none' }}>
              {label}
            </FormLabel>}
            <RadioGroup
              {...field}
              name={name}
              row={row}
              onChange={(_, value) => {
                field.onChange(value);
                onChangeValue?.(value);
              }}
            >
              {options.map((item) => (
                <FormControlLabel
                  key={item.value}
                  value={item.value}
                  control={<Radio size={size} disabled={disabled || item.disabled} />}
                  label={item.label}
                />
              ))}
            </RadioGroup>
            {(error || helperText) && (
              <FormHelperText>
                {error?.message || helperText}
              </FormHelperText>
            )}
          </FormControl>
        )}
      />
    </Box>
  );
};

export default RadioFormField;