import { FormControl, FormHelperText } from '@mui/material'
import Checkbox from '@mui/material/Checkbox'
import FormControlLabel from '@mui/material/FormControlLabel'
import FormGroup from '@mui/material/FormGroup'
import { useTheme } from '@mui/styles'
import { FieldInputProps, FormikProps } from 'formik'
import _get from 'lodash/get'
import React from 'react'

interface ICheckboxField {
  label: string | number | JSX.Element;
  field: FieldInputProps<any>;
  form: FormikProps<any>;
}

export const CheckboxField = ({
  label,
  field,
  form: { touched, errors },
}: ICheckboxField) => {
  const isTouched = Boolean(_get(touched, field.name, false))
  const errorText = _get(errors, field.name)
  const hasError = isTouched && Boolean(errorText)
  const customTheme: any = useTheme()

  return (
    <FormControl
      className={`checkbox-field ${hasError ? 'required-checkbox-field' : ''}`}
      error={hasError}
    >
      <FormGroup>
        <FormControlLabel
          control={<Checkbox {...field} checked={Boolean(field.value)} />}
          label={label}
          componentsProps={{ typography: customTheme?.checkbox }}
        />
      </FormGroup>
      {hasError && <FormHelperText>Required</FormHelperText>}
    </FormControl>
  )
}
