import React, { useRef, useState } from 'react';
import { useClickOutside } from '../../../hooks/useClickOutside';
import Style from './Dropdown.style';

interface IPropsDropDown extends React.ComponentProps<any> {
   menu: any[];
}

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

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

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

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

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