import React, { useImperativeHandle, useRef, useState } from 'react';
import {
   AutocompletePure,
   IComponentAutoCompleteAs,
   IPropsAutoComplete,
   IRefAutoCompleteAs,
} from '../AutocompletePure';
import { Input } from '../Input';
import { IAutoCompleteProps } from './Autocomplete.interface';

const InputAutoComplete = React.forwardRef<IRefAutoCompleteAs, IComponentAutoCompleteAs<IAutoCompleteProps>>(
   function InputAutoComplete(
      { _handleInputChange, _openAutoComplete, _closeAutoComplete, _loading, cleanAfterSelect, ...rest },
      ref,
   ): JSX.Element {
      const inputRef = useRef<HTMLInputElement>();

      useImperativeHandle(ref, () => ({
         onSelect(item) {
            if (cleanAfterSelect) {
               inputRef.current.value = '';
               if (rest.onInput) rest.onInput('');
            } else {
               inputRef.current.value = item.name;
               if (rest.onInput) rest.onInput(item.name);
            }
         },
      }));

      function onInput(value: string): void {
         _handleInputChange(value);
         if (rest.onInput) rest.onInput(value);
      }

      function onFocus(e: any): void {
         _openAutoComplete();
         if (rest.onFocus) rest.onFocus(e);
      }

      function onBlur(e: any): void {
         _closeAutoComplete();
         if (rest.onBlur) rest.onBlur(e);
      }

      return (
         <Input
            {...rest}
            ref={inputRef}
            onInput={onInput}
            onFocus={onFocus}
            onBlur={onBlur}
            loading={_loading}
            data-testid="autocomplete--input"
         />
      );
   },
);

export function Autocomplete(props: IPropsAutoComplete<IAutoCompleteProps>): JSX.Element {
   return <AutocompletePure {...props} as={InputAutoComplete} />;
}
