import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useEffect, useRef } from 'react';
import { AutocompleteResults } from '@assets/js-shop/autocomplete/AutocompleteResults';
import { AutocompletePresearch } from '@assets/js-shop/autocomplete/AutocompletePresearch';
import { IGraphQLAutocompleteResult } from '@assets/interfaces/gqlApi/graphql';
import { useAutocomplete } from '@assets/js-shop/autocomplete/useAutocomplete';
import config from '@assets/js-shop/config';

export interface AutocompleteData {
   [key: string]: IGraphQLAutocompleteResult;
}

export function Autocomplete() {
   const { active, search, presearchData, inputHandlers } = useAutocomplete();
   const element = useRef<HTMLDivElement>();

   useEffect(() => {
      const component = document.querySelector(config.autocompleteParentSelector) as HTMLElement;
      const form = component?.querySelector('form') as HTMLFormElement;
      const input = component?.querySelector('input[name="search"]') as HTMLInputElement;

      if (!input || !form) {
         console.log(
            'jsShop: Cannot initialize autocomplete: js-shop-autocomplete element not found',
         );

         return;
      }

      input.addEventListener('input', inputHandlers.handleInputChange as EventListener);
      input.addEventListener(
         'focusin',
         inputHandlers.handleInputFocusIn as unknown as EventListener,
      );
      component.addEventListener(
         'focusout',
         inputHandlers.handleInputFocusOut as unknown as EventListener,
      );

      element.current = document.createElement('div');
      element.current.classList.add('autocomplete-wrapper');
      form.after(element.current);

      return () => {
         input.removeEventListener('input', inputHandlers.handleInputChange as EventListener);
         input.removeEventListener(
            'focusin',
            inputHandlers.handleInputFocusIn as unknown as EventListener,
         );
         component.removeEventListener(
            'focusout',
            inputHandlers.handleInputFocusOut as unknown as EventListener,
         );
      };
   }, []);

   const renderAutocomplete = (): React.JSX.Element => {
      return (
         <>
            <div
               className={`autocomplete ${active ? 'opened' : ''}`}
               tabIndex={0}>
               <div className="autocomplete-inner">
                  {!search.value && <AutocompletePresearch data={presearchData} search={search.value} />}
                  {search.value && !search.loading && <AutocompleteResults data={search.data} search={search.value} />}
                  {search.loading && (
                     <div className="loader">
                        <span className="loader-icon"></span>
                     </div>
                  )}
               </div>
            </div>
         </>
      );
   };

   if (!element.current) {
      return '';
   }

   return ReactDOM.createPortal(renderAutocomplete(), element.current);
}
