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

import { FormControllerFieldProps } from './types';

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

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