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

import Checkbox from '@material-hu/mui/Checkbox';
import FormControlLabel from '@material-hu/mui/FormControlLabel';

export type CheckboxControlProps = {
  label: string;
  name: string;
  control?: any;
  defaultValue?: any;
  isReadOnly?: boolean;
};

export const CheckboxControl: FC<CheckboxControlProps> = props => {
  const {
    label,
    name,
    control = null,
    defaultValue = null,
    isReadOnly = false,
  } = props;

  if (!isReadOnly) {
    return (
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={field.value}
                onChange={e => field.onChange(e.target.checked)}
              />
            }
            label={label}
            labelPlacement="start"
            sx={{ mt: 2, mb: 1 }}
          />
        )}
      />
    );
  }

  return (
    <FormControlLabel
      control={<Checkbox checked={defaultValue} />}
      label={label}
      labelPlacement="start"
      sx={{ mt: 2, mb: 1 }}
    />
  );
};

export default CheckboxControl;
