import { FC, ReactNode } from 'react';
import { useFormContext, Controller } from 'react-hook-form';

import Checkbox, { CheckboxProps } from '@material-hu/mui/Checkbox';
import FormControlLabel from '@material-hu/mui/FormControlLabel';

export type FormCheckboxInputProps = CheckboxProps & {
  label: ReactNode;
};

export const FormCheckboxInput: FC<FormCheckboxInputProps> = props => {
  const { label, name, ...other } = props;

  const { control } = useFormContext();

  return (
    <FormControlLabel
      control={
        <Controller
          render={({ field: { value, ...field } }) => (
            <Checkbox
              checked={!!value}
              {...field}
              {...other}
            />
          )}
          name={name}
          control={control}
        />
      }
      label={label}
      disabled={other.disabled}
    />
  );
};

export default FormCheckboxInput;
