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

import Box from '@material-hu/mui/Box';
import TextField from '@material-hu/mui/TextField';
import Typography from '@material-hu/mui/Typography';

import { Field } from 'src/types/nemakEvents';

import { useTranslation } from '../i18n';

export type TextBoxControllerProps = {
  field: Field;
};

export const TextBoxController: FC<TextBoxControllerProps> = props => {
  const { field } = props;

  const { t } = useTranslation();
  const {
    control,
    formState: { errors },
  } = useFormContext();

  const { FieldName, FieldDisplayName, EventExtraFieldId } = field;

  return (
    <Controller
      key={EventExtraFieldId}
      name={EventExtraFieldId.toString()}
      control={control}
      rules={{ required: t('REQUIRED_FIELD') }}
      render={({ field: renderField }) => (
        <>
          <TextField
            key={EventExtraFieldId}
            label={FieldDisplayName}
            fullWidth
            margin="normal"
            {...renderField}
          />
          {errors[FieldName] && (
            <Box sx={{ mb: 1 }}>
              <Typography sx={{ color: 'red' }}>
                {t('REQUIRED_FIELD')}
              </Typography>
            </Box>
          )}
        </>
      )}
    />
  );
};

export default TextBoxController;
