import FormControl from '@mui/material/FormControl'
import FormControlLabel from '@mui/material/FormControlLabel'
import FormHelperText from '@mui/material/FormHelperText'
import FormLabel from '@mui/material/FormLabel'
import Radio from '@mui/material/Radio'
import RadioGroup from '@mui/material/RadioGroup'
import { FieldInputProps, FormikProps } from 'formik'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import React from 'react'

export interface IRadio {
  id: string | number;
  label: string | number;
  value: string | number;
  [key: string]: any;
}

export interface IRadioGroupField {
  label?: string;
  field: FieldInputProps<any>;
  form: FormikProps<any>;
  radios: IRadio[];
  disabled?: boolean;
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

export const RadioGroupField = ({
  label,
  field,
  radios = [],
  disabled,
  form: { touched, errors, setFieldValue },
  onChange = _identity,
}: IRadioGroupField) => {
  const radioId = `radio-${field.name}`
  const error = _get(errors, field.name)
  const isTouched = Boolean(_get(touched, field.name))

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target as HTMLInputElement
    setFieldValue(field.name, value)
    onChange(e)
  }

  if (!radios) return null

  return (
    <FormControl disabled={disabled} error={isTouched && Boolean(error)}>
      {isTouched && Boolean(error) ? (
        <FormHelperText className="radio-error" error>
          {error}
        </FormHelperText>
      ) : null}
      {label && <FormLabel id={radioId}>{label}</FormLabel>}
      <RadioGroup
        aria-labelledby={radioId}
        name={field.name}
        value={field.value}
        onChange={handleChange}
      >
        {radios.map(radio => {
          const { id, label, value } = radio
          return (
            <FormControlLabel
              key={id}
              label={label}
              value={value}
              control={<Radio />}
            />
          )
        })}
      </RadioGroup>
    </FormControl>
  )
}
