import React, { useEffect, useRef, useState } from 'react';
import { useField } from '@unform/core';
import { Autocomplete } from '../Autocomplete';
import Style from './InputAutoComplete.style';

interface IInputAutoCompleteProps extends React.ComponentProps<any> {
   renderInput?: (params: any) => any;
   name: any;
   prefix?: any;
   fetch?: any;
   value?: string;
   getValue?: (i: any) => any;
   getValueText: (i: any) => string;
   title?: any;
}

export const InputAutoComplete: React.FunctionComponent<IInputAutoCompleteProps> = ({
   name,
   fetch,
   title,
   prefix,
   getValueText,
   getValue,
   renderInput,
}) => {
   const autocompleteRef = useRef<any>();
   const { registerField, defaultValue = '', error, fieldName } = useField(name);

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: autocompleteRef.current,
         path: 'value' as any,
         setValue(ref: any, value: string) {
            ref = value;
         },
         getValue(ref: any) {
            return ref;
         },
      });
   }, [fieldName, registerField]);

   useEffect(() => {
      autocompleteRef.current.value = defaultValue;
   }, []);

   return (
      <Style data-cy={`autocomplete-${name}`}>
         <Autocomplete
            ref={autocompleteRef}
            defaultValue={defaultValue}
            name={name}
            title={title}
            fetch={fetch}
            error={!!error}
            prefix={prefix}
            renderInput={renderInput}
            select={(i) => {
               autocompleteRef.current.value = getValueText(i);
            }}
         />

         {!!error && (
            <div className="error-input" data-testid="input-error">
               {error}
            </div>
         )}
      </Style>
   );
};
