/* eslint-disable arrow-body-style */
import React, { useContext, useRef } from 'react';
import PropTypes from 'prop-types';

import Items from '~atoms/menu/items';
import MenuIcon from '~atoms/menu/menu-icon';

import { NavigationContext } from '~organisms/navigation/navigationContext';

import styles from './menu.module.scss';
import keygen from '~helpers/keygen';
import { getMenuObj } from '~helpers/menu';
import { toggleScroll } from '~helpers/scroll';

const Menu = ({
  section,
  menu = 'menu',
  gtmClass = '',
  customStyles,
  orientation = 'horizontal',
  mobileAnimation = 'collapseFull',
  stopScrollOnOpen = true,
  canOpenAllSubMenus = true,
}) => {
  let menuObject;

  const menuListRef = useRef(React.createRef());

  const { setShowSearch, setShowMenu, showMenu, showSearch } = useContext(NavigationContext);

  if (section.modules) {
    menuObject = getMenuObj(section.modules, menu);
  }

  const menuListClasses = `${styles.menuList} ${mobileAnimation ? styles[mobileAnimation] : ''} ${
    orientation ? styles[orientation] : ''
  }`;

  function handleMenuIconClick() {
    if (stopScrollOnOpen) {
      toggleScroll('menu');
    }

    setShowMenu(!showMenu);

    if (showSearch) {
      setShowSearch(false);
      toggleScroll('search');
    }
  }

  return (
    <div className={styles.menuContainer || ''}>
      <MenuIcon onClick={() => handleMenuIconClick()} gtmClass="main-menu-gtm" />
      <ul
        ref={menuListRef}
        className={`${menuListClasses || ''} ${showMenu && (styles.show || '')} ${
          styles[customStyles] || ''
        }`}
        role="menu"
      >
        {menuObject &&
          menuObject.children.map((child) => {
            const level = 1;
            return (
              <Items
                menuListRef={menuListRef}
                gtmClass={gtmClass}
                key={keygen()}
                item={child}
                canOpenAllSubMenus={canOpenAllSubMenus}
                level={level}
              />
            );
          })}
      </ul>
    </div>
  );
};

Menu.propTypes = {
  section: PropTypes.shape({
    modules: PropTypes.arrayOf(
      PropTypes.shape({
        menu_short_code: PropTypes.string,
        children: PropTypes.arrayOf(
          PropTypes.shape({
            title: PropTypes.string,
            value: PropTypes.string,
          })
        ),
      })
    ),
  }).isRequired,
  menu: PropTypes.string,
  gtmClass: PropTypes.string,
  customStyles: PropTypes.string,
  orientation: PropTypes.oneOf(['horizontal']),
  mobileAnimation: PropTypes.oneOf(['collapseFull', 'collapse', 'slideLeft', 'slideTop']),
  stopScrollOnOpen: PropTypes.bool,
  canOpenAllSubMenus: PropTypes.bool,
};

export default Menu;
