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

import Switch from '@mui/material/Switch';
import FormHelperText from '@mui/material/FormHelperText';
import FormControlLabel from '@mui/material/FormControlLabel';

import { IRHFSwitchProps } from '../types';

/**
 * @description {RHFSwitch} - A RHFSwitch component for handling switch input with form control and validation.
 * @param {string} name - The name of the switch input
 * @param {string} helperText - The helper text for the input
 * @param {Object} other - Other props for the switch input
 * @return {ReactNode} The JSX for the RHFSwitch component
 */
export const RHFSwitch = ({ name, helperText, ...other }: IRHFSwitchProps) => {
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <div>
          <FormControlLabel control={<Switch {...field} checked={field.value} />} {...other} />

          {(!!error || helperText) && (
            <FormHelperText error={!!error}>{error ? error?.message : helperText}</FormHelperText>
          )}
        </div>
      )}
    />
  );
};
