import React from 'react';
import { MuiOtpInput } from 'mui-one-time-password-input';
import { Controller, useFormContext } from 'react-hook-form';

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

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

/**
 * @description {RHFCode} - Renders a component for React Hook Form (RHF) code input.
 * @param {IRHFCodesProps} props - The props for the component.
 * @returns {JSX.Element} - The rendered component.
 */
export const RHFCode = ({ name, ...other }: IRHFCodesProps) => {
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <div>
          <MuiOtpInput
            {...field}
            autoFocus
            gap={1.5}
            length={6}
            TextFieldsProps={{
              error: !!error,
              placeholder: '-',
            }}
            {...other}
          />

          {error && (
            <FormHelperText sx={{ px: 2 }} error>
              {error.message}
            </FormHelperText>
          )}
        </div>
      )}
    />
  );
};
