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

import TextField from '@mui/material/TextField';

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

/**
 *  @description {RHFTextField} - Generate a controlled text field for react-hook-form.
 * @param {string} name - The name of the input field
 * @param {React.ReactNode} helperText - The helper text to display
 * @param {TextFieldProps} type - The type of the input field
 * @param {object} ...other - Other props for the TextField component
 * @return {JSX.Element} The controlled TextField component
 */
export const RHFTextField = ({ name, helperText, type, ...other }: IRHFTextFieldProps) => {
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <TextField
          {...field}
          fullWidth
          type={type}
          value={type === 'number' && field.value === 0 ? '' : field.value}
          onChange={(event) => {
            if (type === 'number') {
              field.onChange(Number(event.target.value));
            } else {
              field.onChange(event.target.value);
            }
          }}
          error={!!error}
          helperText={error ? error?.message : helperText}
          {...other}
        />
      )}
    />
  );
};
