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

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

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

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

   const [referenceElement, setReferenceElement] = useState(null);
   const [popperElement, setPopperElement] = useState(null);
   const { styles, attributes } = usePopper(referenceElement, popperElement, {
      modifiers: [
         {
            name: 'preventOverflow',
            options: {
               altAxis: false, // false by default
            },
         },
         {
            name: 'offset',
            options: {
               offset: [0, 0],
            },
         },
      ],
   });

   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-testid="dropdown" ref={dropdownRef} className="dropdown-container">
         <span onClick={toggleMenu} data-testid="dropdown-btn" ref={setReferenceElement}>
            {children}
         </span>
         {open && (
            <div
               className="ds-dropdown-menu"
               data-testid="dropmenu-popup"
               ref={setPopperElement}
               style={styles.popper}
               {...attributes.popper}
            >
               {Header && <Header />}
               {options.map((e, i) => (
                  <div
                     key={i}
                     onClick={() => (e.disabled ? setOpen(false) : clickItem(e))}
                     className={`menu-item ${e.disabled ? 'disabled' : ''}`}
                     data-testid={`dropmenu-menu-${i}`}
                  >
                     {e.name}
                  </div>
               ))}
            </div>
         )}
      </Style>
   );
};
