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

import FormControlLabel, {
  FormControlLabelProps,
} from '@material-hu/mui/FormControlLabel';
import Switch, { SwitchProps } from '@material-hu/mui/Switch';
import Typography, { TypographyProps } from '@material-hu/mui/Typography';

export type FormSwitchProps = SwitchProps & {
  label?: string;
  subLabel?: string;
  formControlLabelProps?: Partial<FormControlLabelProps>;
  labelProps?: TypographyProps;
};

function FormSwitch(props: FormSwitchProps) {
  const { control } = useFormContext();
  const {
    name,
    label,
    subLabel,
    formControlLabelProps,
    disabled,
    labelProps,
    ...other
  } = props;
  return (
    <FormControlLabel
      control={
        <Controller
          render={({ field }) => (
            <Switch
              {...other}
              {...field}
              onChange={(event, checked) => {
                field.onChange(event);
                other.onChange?.(event, checked);
              }}
              checked={!!field.value}
              defaultValue={field.value}
              disabled={disabled}
            />
          )}
          name={name}
          control={control}
        />
      }
      label={
        label && (
          <div>
            <Typography
              gutterBottom
              variant="subtitle2"
              sx={{
                mb: 0,
                color: theme => disabled && theme.palette.text.disabled,
              }}
              {...labelProps}
            >
              {label}
            </Typography>
            {subLabel && (
              <Typography
                color="textSecondary"
                variant="body2"
              >
                {subLabel}
              </Typography>
            )}
          </div>
        )
      }
      {...formControlLabelProps}
    />
  );
}

export default FormSwitch;
