import React, { useEffect, useRef, useState } from 'react';
import { useClickOutside } from '@devesharp/react-hooks';
import { GetScrollParent } from '@devesharp/react-utils';
import Style from './Dropdown.style';

export interface IPropsDropDownOption {
   name: string | JSX.Element;
   value: any;
}

export interface IPropsDropDown {
   options: IPropsDropDownOption[];
   onClick: (v: IPropsDropDownOption) => void;
   children?: any;
}

export const Dropdown: React.FunctionComponent<IPropsDropDown> = ({ children, options, onClick }: IPropsDropDown) => {
   const [open, setOpen] = useState(false);
   const dropdownRef = useRef(null);

   useClickOutside(() => setOpen(false), dropdownRef);

   function toggleMenu(): void {
      setOpen(!open);
   }

   function clickItem(item: IPropsDropDownOption): void {
      setOpen(false);
      onClick(item);
   }

   /**
    * Envia para posição do datepicker
    */
   useEffect(() => {
      if (open) {
         const el = document.getElementsByClassName('ds-dropdown-menu')[0];

         const scrollParent = GetScrollParent(dropdownRef.current.parentNode);

         const { top: topMain, height: heightMain } = dropdownRef.current.getBoundingClientRect();
         const { height: heightScroll } = scrollParent.getBoundingClientRect();

         if (topMain + heightMain + el.getBoundingClientRect().height > heightScroll) {
            if (el.scrollIntoView) el.scrollIntoView({ block: 'end', behavior: 'smooth' });
         }
      }
   }, [open]);

   return (
      <Style data-cy="dropdown" ref={dropdownRef}>
         <span onClick={toggleMenu} data-cy="dropdown-btn">
            {children}
         </span>
         {open && (
            <div className="ds-dropdown-menu" data-testid="dropmenu-popup">
               {options.map((e, i) => (
                  <div key={i} onClick={() => clickItem(e)} className="menu-item" data-testid={`dropmenu-menu-${i}`}>
                     {e.name}
                  </div>
               ))}
            </div>
         )}
      </Style>
   );
};
