import React from 'react';

import Radio, { RadioProps } from '@mui/material/Radio';
import FormControlLabel from '@mui/material/FormControlLabel';

import { bem } from 'utils/bem';

import { RadioButtonProps } from './types';
import { RadioButtonView } from './components';
import { THEME } from '../../constants';

import styles from './radio-button.scss';

export const radioClassName = bem(styles, 'radio-button');

export const RadioButton = <T extends string | number>({
  value,
  name,
  theme = THEME.light,
  label,
  disabled,
  checked,
  required,
  hasError = false,
  className,
  radioButtonClassName,
  dataAttributes,
  ...otherProps
}: RadioButtonProps<T>): JSX.Element => {
  const icon = (
    <RadioButtonView
      theme={theme}
      hasError={hasError}
    />
  );

  const checkedIcon = (
    <RadioButtonView
      checked
      theme={theme}
      hasError={hasError}
    />
  );

  const RadioButtonComponent = (): JSX.Element => (
    <Radio
      {...dataAttributes}
      value={value}
      name={name}
      disableRipple
      icon={icon}
      checkedIcon={checkedIcon}
      className={radioButtonClassName}
      required={required}
      checked={checked}
      disabled={disabled}
      {...(otherProps as RadioProps)}
    />
  );

  return (
    <FormControlLabel
      value={value}
      disabled={disabled}
      control={<RadioButtonComponent />}
      className={radioClassName(null, { [theme]: true, hasError }, className)}
      label={label}
    />
  );
};
