/* eslint-disable import/no-named-as-default */
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import Link from '~hooks/link';
import Menu from '~molecules/menu';
import { toggleScroll } from '~helpers/scroll';
import ConditionalWrapper from '~atoms/conditional-wrapper';
import Sticky from '~molecules/sticky';

import NavigationProvider from './navigationContext';

import styles from './navigation.module.scss';

const Navigation = ({
  section,
  pageContext,
  hasSearch = true,
  sticky = true,
  orientation = 'horizontal',
  mobileAnimation = 'collapseFull',
  stopScrollOnOpen = true,
  canOpenAllSubMenus = true,
  logo = '../../../../../images/logo.svg',
  logoWidth = 200,
  logoHeight = 31,
  searchIcon = null,
  template,
  children,
  customStyles,
  hasCustomComponent = false,
}) => {
  const navRef = useRef(React.createRef());
  const showMenu = template !== 'ppc';

  let searchURLPageName = 's';

  const Search = hasSearch ? loadable(() => import('~organisms/search')) : null;
  const CustomComponent = hasCustomComponent
    ? loadable(() => import('~atoms/menu/variables'))
    : null;
  const logoImg = (
    <img
      alt={`${process.env.GATSBY_SITE_NAME} logo`}
      src={logo}
      width={logoWidth}
      height={logoHeight}
    />
  );

  if (stopScrollOnOpen) toggleScroll('', true);

  const activeMarket = pageContext?.allMarkets && pageContext?.allMarkets[pageContext.page.market];
  if (activeMarket) activeMarket.market = pageContext?.page?.market;

  if (activeMarket?.path_prefix) {
    searchURLPageName = `${activeMarket?.path_prefix}/s`;
  }

  const onClickHandler = () => {
    if (
      typeof window !== 'undefined' &&
      window.location.href.replace(window.location.origin, '') === '/'
    ) {
      window.location.reload();
    }
  };

  return (
    <ConditionalWrapper
      condition={sticky}
      wrapper={(items) => (
        <Sticky position="top" fullWidth showOnScroll={false} className={styles.stickyNav || ''}>
          {items}
        </Sticky>
      )}
    >
      <nav className={styles.nav || ''} ref={navRef}>
        <NavigationProvider>
          {showMenu ? (
            <Link
              className={`${styles.logo || ''} main-menu-gtm logo-cta`}
              aria-label="Nav Logo"
              to={activeMarket?.path_prefix || '/'}
              onClick={onClickHandler}
            >
              {logoImg}
            </Link>
          ) : (
            logoImg
          )}
          {showMenu && (
            <>
              <Menu
                section={section}
                orientation={orientation}
                mobileAnimation={mobileAnimation}
                stopScrollOnOpen={stopScrollOnOpen}
                canOpenAllSubMenus={canOpenAllSubMenus}
                customStyles={customStyles}
                gtmClass="main-menu-gtm"
              />

              {hasSearch && (
                <Search
                  className={styles.search || ''}
                  searchIcon={searchIcon}
                  pageContext={pageContext}
                  searchURLPageName={searchURLPageName}
                />
              )}
              {CustomComponent && <CustomComponent pageContext={pageContext} section={section} />}
            </>
          )}
        </NavigationProvider>
      </nav>
      {children}
    </ConditionalWrapper>
  );
};

Navigation.propTypes = {
  section: PropTypes.shape({
    modules: PropTypes.arrayOf(
      PropTypes.shape({
        short_code: PropTypes.string,
        children: PropTypes.arrayOf(
          PropTypes.shape({
            title: PropTypes.string,
            value: PropTypes.string,
          })
        ),
      })
    ),
  }).isRequired,
  pageContext: PropTypes.shape({
    allMarkets: PropTypes.shape({}),
    page: PropTypes.shape({
      market: PropTypes.shape({}),
    }),
  }),
  hasSearch: PropTypes.bool,
  sticky: PropTypes.bool,
  orientation: PropTypes.oneOf(['horizontal']),
  mobileAnimation: PropTypes.oneOf(['collapseFull', 'collapse', 'slideLeft', 'slideTop']),
  stopScrollOnOpen: PropTypes.bool,
  canOpenAllSubMenus: PropTypes.bool,
  template: PropTypes.string,
  logo: PropTypes.string,
  logoWidth: PropTypes.number,
  logoHeight: PropTypes.number,
  searchIcon: PropTypes.string,
  children: PropTypes.node,
  customStyles: PropTypes.string,
  hasCustomComponent: PropTypes.bool,
};

export default Navigation;
