import {
  Box,
  BoxProps,
  FormControlLabel,
  FormHelperText,
  RadioGroup as MuiRadioGroup,
  Radio,
  RadioGroupProps,
  styled,
} from '@mui/material'
import { ReactNode } from 'react'
import FormLabel from './FormLabel'

const BpIcon = styled('span')(({ theme }) => ({
  borderRadius: '50%',
  width: 18,
  height: 18,
  border: '1px solid #CBCBCB',
  backgroundColor: '#f8f8f8',
  '.Mui-focusVisible &': {
    outline: '2px auto rgba(19,124,189,.6)',
    outlineOffset: 2,
  },
  'input:hover ~ &': {
    backgroundColor: '#f8f8f8',
  },
  'input:disabled ~ &': {
    boxShadow: 'none',
    background: 'rgba(206,217,224,.5)',
  },
}))

const BpCheckedIcon = styled(BpIcon)(({ theme }) => ({
  border: '1px solid #609D52',
  background: '#f8f8f8',
  backgroundImage:
    'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',
  '&:before': {
    backgroundColor: '#609D52',
    content: '""',
    display: 'block',
    width: 8,
    height: 8,
    margin: '4px',
    left: '2px',
    borderRadius: '50%',
  },
  'input:hover ~ &': {
    backgroundColor: '#f8f8f8',
  },
}))

interface Props extends RadioGroupProps {
  label: string | ReactNode
  name?: string
  control?: any
  sx?: any
  row?: boolean
  required?: boolean
  options: { value: any; label: string | ReactNode; disabled?: boolean }[]
  containerProps?: BoxProps
  error?: boolean
  helperText?: string | null
  disabled?: boolean
}

export default function RadioGroup(props: Props) {
  const {
    name,
    label,
    options = [],
    row = false,
    required = false,
    value,
    onChange,
    containerProps,
    error,
    helperText,
    disabled,
    ...rest
  } = props
  return (
    <Box width="100%" {...containerProps}>
      <FormLabel label={label} name={name} required={required} />
      <MuiRadioGroup
        value={value}
        onChange={onChange}
        row={row}
        name={name}
        {...rest}
      >
        {options.map((item, index) => (
          <FormControlLabel
            key={index}
            value={item.value}
            control={
              <Radio
                checkedIcon={<BpCheckedIcon />}
                icon={<BpIcon />}
                disabled={disabled || item.disabled}
              />
            }
            label={item.label}
          />
        ))}
      </MuiRadioGroup>
      {error && <FormHelperText>{helperText}</FormHelperText>}
    </Box>
  )
}
