import * as React from 'react';
import { useState, useEffect } from 'react';
import AnimateHeight from 'react-animate-height';
import { NavLink, useHistory } from 'react-router-dom';
import { faChevronDown } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { UserAvatar } from '../UserAvatar';
import { PHeader, SHeader } from './HeaderVertical.interface';
import * as S from './HeaderVertical.style';

/**
 * Component Header
 * @param props
 * @constructor
 */
export const HeaderVertical: React.FunctionComponent<PHeader> = (props) => {
   // eslint-disable-next-line no-underscore-dangle
   const [menuMobile, setMenuMobile] = React.useState(!!(props as any).__menuMobileOpen);
   // eslint-disable-next-line no-underscore-dangle
   const [openUserMenuInfo, setOpenUserMenuInfo] = React.useState(!!(props as any).__openUserMenuInfo);

   const history = useHistory();

   // fechar menu quando url mudar
   useEffect(() => {
      history.listen((location, action) => {
         setMenuMobile(false);
      });
   }, []);

   //
   const toggleMenuMobile = (): any => setMenuMobile(!menuMobile);
   const closeUserMenuInfo = (): any => setOpenUserMenuInfo(false);
   const toggleUserMenuInfo = (): any => setOpenUserMenuInfo(!openUserMenuInfo);

   //
   const sharedProps = {
      ...props,
      menuMobile,
      openUserMenuInfo,
      toggleMenuMobile,
      closeUserMenuInfo,
      toggleUserMenuInfo,
   };

   const [subMenuOpen, setSubMenuOpen] = useState(-1);

   return (
      <S.Container open={menuMobile}>
         <div className="logo-container">
            <div className="d-flex align-items-center">
               <div className="menu-icon">
                  <div className={`ds-menu-hamburger ${menuMobile ? 'open' : ''}`} onClick={toggleMenuMobile}>
                     <span />
                     <span />
                     <span />
                  </div>
               </div>
               <div className="flex-fill">
                  {!!props.homeLink && (
                     <NavLink to={{ pathname: props.homeLink }} exact>
                        <div className="ds-logo">
                           <img src={props.logo} alt="" />
                        </div>
                     </NavLink>
                  )}

                  {!props.homeLink && (
                     <div className="ds-logo">
                        <img src={props.logo} alt="" />
                     </div>
                  )}
               </div>
               <div className="actions-container">{props.actionsElements}</div>
            </div>
         </div>

         <div className="username-container">
            <div className="user-image-container">
               <UserAvatar user={props.user} sizeCircle={50} />
            </div>
            <div className="username-name">
               <span className="username">{props.user?.name}</span>
               <div className="role">{props.user?.role || 'Usuário'}</div>

               {props.myAccountRoute && (
                  <div className="text-left">
                     <NavLink
                        key={props.myAccountRoute}
                        className="ds-item"
                        to={{ pathname: props.myAccountRoute }}
                        exact
                     >
                        Meu Perfil
                     </NavLink>
                  </div>
               )}
            </div>
         </div>

         <div className="menu-container">
            {props.menu.map((item: any, i): any => (
               <span key={`${item.route}-${i}`}>
                  {item == 'division' && <hr />}
                  {!item?.subMenu && item != 'division' && <Menu {...item} />}
                  {!!item?.subMenu && (
                     <SubMenu
                        {...item}
                        open={subMenuOpen == i}
                        openSubmenu={() => setSubMenuOpen(i)}
                        closeSubmenu={() => setSubMenuOpen(-1)}
                     />
                  )}
               </span>
            ))}
         </div>
      </S.Container>
   );
};

const Menu: React.FunctionComponent<any> = (props) => {
   if (props.titleCategory) {
      return <div className="title-category">{props.title}</div>;
   }

   return (
      <NavLink className="menu-item" activeClassName="active" to={{ pathname: props.route }} exact>
         <div className="title">{props.title}</div>
      </NavLink>
   );
};

const SubMenu: React.FunctionComponent<any> = (props) => {
   const isSubRoute = (location, subMenu: any): boolean => {
      return !subMenu.every((item) => item.route !== location.pathname);
   };

   useEffect(() => {
      if (isSubRoute(window.location, props.subMenu)) {
         props.openSubmenu();
      }
   }, []);

   return (
      <div className={`menu-category ${!props.open || 'open'}`}>
         <NavLink
            key={props.route}
            className={`menu-item ${!props.open || 'open'}`}
            activeClassName="menu-item-active"
            to={{
               pathname: props.route,
            }}
            onClick={(e) => {
               e.preventDefault();
               if (props.open) {
                  props.closeSubmenu();
               } else {
                  props.openSubmenu();
               }
            }}
            isActive={(match, location) => isSubRoute(location, props.subMenu)}
         >
            <div className="title">{props.title}</div>
            <div className="caret">
               <FontAwesomeIcon icon={faChevronDown} flip="horizontal" />
            </div>
         </NavLink>

         <AnimateHeight id="example-panel" duration={500} height={props.open ? 'auto' : 0}>
            <div className="menu-subcategory">
               {props.subMenu.map((subItem, i): any => (
                  <NavLink
                     key={`${subItem.route}-${i}`}
                     className="item"
                     activeClassName="active"
                     to={{
                        pathname: subItem.route,
                     }}
                     exact
                  >
                     {subItem.title}
                  </NavLink>
               ))}
            </div>
         </AnimateHeight>
      </div>
   );
};
