import React from 'react';
import {
  FormControl,
  FormLabel,
  FormErrorMessage,
  FormHelperText,
} from '@chakra-ui/react';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { FormInputFieldProps } from './types';

export const FormInputField = ({
  control,
  name,
  label,
  isRequired,
  rules,
  errors,
  Input,
  inputProps,
  help,
}: FormInputFieldProps) => {
  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.order-create.form.field',
  });
  const fieldErrors = errors[name];

  return (
    <FormControl isRequired={label && isRequired} isInvalid={!!fieldErrors}>
      {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
      <Controller
        control={control}
        name={name}
        rules={{
          required: isRequired && t('validation.required'),
          ...rules,
        }}
        render={({ field }) => (
          <Input variant='filled' {...field} {...inputProps} />
        )}
      />
      <FormErrorMessage>{fieldErrors?.message}</FormErrorMessage>
      {help && <FormHelperText>{help}</FormHelperText>}
    </FormControl>
  );
};