import { 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';
import { TypographyProps } from '@material-hu/mui/Typography';

type Props = CheckboxProps & {
  label: ReactNode;
  typographyProps?: TypographyProps;
  onSelect?: CheckboxProps['onChange'];
  name: string;
};

function FormCheckbox({
  label,
  name,
  typographyProps,
  onSelect,
  ...other
}: Props) {
  const { control } = useFormContext();
  return (
    <FormControlLabel
      control={
        <Controller
          render={({ field: { value, onChange, ...field } }) => (
            <Checkbox
              checked={!!value}
              onChange={(...args) => {
                onChange(...args);
                onSelect?.(...args);
              }}
              {...field}
              {...other}
            />
          )}
          name={name}
          control={control}
        />
      }
      label={label}
      slotProps={{ typography: typographyProps }}
      disabled={other.disabled}
    />
  );
}

export default FormCheckbox;
