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

import Slider from '@mui/material/Slider';
import FormHelperText from '@mui/material/FormHelperText';

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

/**
 * @description {RHFSlider} - Renders a RHFSlider component.
 * @param {string} name - The name of the slider control.
 * @param {React.ReactNode} helperText - The helper text to display below the slider.
 * @param {Object} other - Additional props to pass to the Slider component.
 * @returns {JSX.Element} The rendered RHFSlider component.
 */
export const RHFSlider = ({ name, helperText, ...other }: IRHFSliderProps) => {
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <>
          <Slider {...field} valueLabelDisplay="auto" {...other} />

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