import { useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import { useAuth } from 'src/contexts/JWTContext';
import { getAnswerAutocompleteField } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

type SurveyAutocompleteInputProps = {
  name: string;
  userField: string;
};

const AutocompleteInput = ({
  name,
  userField,
}: SurveyAutocompleteInputProps) => {
  const { setValue } = useFormContext();
  const { user } = useAuth();
  const { t } = useLokaliseTranslation(['forms']);

  useEffect(() => {
    const value = getAnswerAutocompleteField(userField, undefined, user, t);
    if (value !== undefined && value !== null) {
      setValue(name, value);
    }
  }, [name, userField, setValue, user, t]);

  return (
    <FormInputClassic
      name={name}
      inputProps={{
        disabled: true,
        hasCounter: false,
      }}
    />
  );
};

export default AutocompleteInput;
