import React, { useCallback } from 'react';

import RadioGroup from '@mui/material/RadioGroup';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';

import { Typography, TYPOGRAPHY_TYPE } from 'components';

import { THEME } from '../../constants';
import { RadioButtonGroupProps } from './types';

export const RadioButtonGroup = <T extends string>({
  value,
  label,
  name,
  onChange,
  className,
  children,
  dataAttributes,
  theme = THEME.light,
}: React.PropsWithChildren<RadioButtonGroupProps<T>>): JSX.Element => {
  const handleChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>, newValue: string) => {
      onChange(newValue);
    },
    [onChange],
  );

  return (
    <FormControl>
      {label && (
        <FormLabel>
          <Typography
            type={TYPOGRAPHY_TYPE.body3}
            theme={theme}
          >
            {label}
          </Typography>
        </FormLabel>
      )}
      <RadioGroup
        {...dataAttributes}
        value={value}
        name={name}
        className={className}
        onChange={handleChange}
      >
        {children}
      </RadioGroup>
    </FormControl>
  );
};
