/* eslint-disable camelcase */
/* eslint-disable no-useless-concat */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import { v4 as uuidv4 } from 'uuid';
import { getSection } from 'gatsby-core-theme/src/helpers/getters';
import Navigation from 'gatsby-core-theme/src/components/organisms/navigation';
import ScrollToTop from 'gatsby-core-theme/src/components/atoms/scroll-to-top';
import Main from 'gatsby-core-theme/src/components/molecules/main';
import Header from 'gatsby-core-theme/src/components/molecules/header';
import isSticky from 'gatsby-core-theme/src/hooks/stickyOnScroll';
import Footer from '../../molecules/footer';
import LinkMenu from '../../../../components/atoms/link-menu';
import { isSearchPath } from '~helpers/isSearchPath';
import { setCookie, getCookie } from '~helpers/cookies';
import styles from './body.module.scss';

function Body({
  pageContext,
  children,
  excludeTemplateInPopup = [],
  hideOperatorBanner = false,
  offsetTop = 400,
}) {
  useEffect(() => {
    if (!getCookie('affUUID')) {
      setCookie('affUUID', uuidv4());
    }
  }, []);

  const getBodySection = (name) => getSection(name, pageContext);
  const [closedBanner, setClosedBanner] = useState(false);
  const getAllMarketsHomepage = () =>
    Object.keys(pageContext?.allMarkets || {})?.map((elm) => elm.split('_')[1]) || [];

  const main = getBodySection('main');
  const navigation = getBodySection('navigation');
  const footer = getBodySection('footer');
  const showScroll = isSticky(offsetTop);

  const links = getBodySection('links');
  const footerNavigationData = pageContext?.marketSections?.footer_navigation || null;
  const isHomePage = pageContext?.page && pageContext?.page.path === '/';
  const pageType = pageContext.page.relation_type;
  const is404 = pageContext.page.path.includes('404');

  const excOperator = navigation?.modules.find((module) => module.name === 'bonus');
  const Popup = pageContext?.marketSections?.popup
    ? loadable(() => import(`../../../../components/organisms/popup`))
    : null;

  const isContactUsPage = !!main?.modules?.filter((module) => module.name === 'contact_form')
    .length;

  const OpenGraph =
    process.env.ENABLE_OPENGRAPH === 'true' && !isHomePage
      ? loadable(() => import(`gatsby-core-theme/src/components/atoms/open-graph`))
      : null;

  const isSearch = isSearchPath(pageContext.allMarkets, pageContext.page.path);

  const status = pageContext.page.relation?.status;

  const hideBanner = status === 'inactive' || status === 'coming_soon';

  const { template, relation_type } = pageContext.page;

  const ExclusiveOperator =
    excOperator && pageType !== 'operator'
      ? loadable(() => import(`../../../../components/molecules/operator-exclusive`))
      : null;

  const popupData = pageContext?.marketSections?.popup?.modules?.find((m) => m.name === 'top_list');
  const FooterNavigation =
    footerNavigationData && pageType !== 'operator'
      ? loadable(() => import(`../../../../components/organisms/footer-navigation`))
      : null;

  const OperatorBanner =
    pageType === 'operator' && !hideBanner && !hideOperatorBanner
      ? loadable(() => import(`gatsby-core-theme/src/components/molecules/bonus/template-two`))
      : null;

  const isPageHomepage =
    getAllMarketsHomepage()?.includes(pageContext?.page?.path) || pageContext?.page?.path === '/';

  const Cookie = loadable(() => import('../../organisms/cookie-consent'));

  return (
    <>
      {navigation && (
        <Navigation
          template={template}
          pageContext={pageContext}
          section={navigation}
          searchIcon="../../../../../../images/search.svg"
          menu="main_menu"
          options={{
            mobile: {
              animation: 'collapseFull',
              closeHandler: null,
              stopScrollOnOpen: true,
              canOpenAllSubMenus: true,
              subMenuDropDownButton: true,
            },
            desktop: {
              orientation: 'horizontal',
            },
          }}
        />
      )}
      {ExclusiveOperator && (
        <ExclusiveOperator bonus={excOperator} template={pageContext?.page?.template} />
      )}
      {FooterNavigation && <FooterNavigation section={footerNavigationData} />}
      {!isSearch && !is404 && (
        <Header exclOperator={ExclusiveOperator !== null} section={pageContext} />
      )}
      {main && !children && (
        <Main exclOperator={ExclusiveOperator !== null} section={main} pageContext={pageContext} />
      )}
      {children && <main>{children}</main>}

      {links && !isContactUsPage && (
        <aside>
          <LinkMenu section={links} />
        </aside>
      )}
      {OpenGraph && <OpenGraph text="Del på" page={pageContext?.page} />}
      {footer && (
        <Footer
          section={footer}
          template={template}
          page={pageContext?.page}
          hasFooterLinks={FooterNavigation !== null}
          footerTemplate={footer.style || 'template_one'}
          dmcaImage="../../../../../../images/dmca.png"
        />
      )}
      {!excludeTemplateInPopup.includes(pageContext?.page?.template) && Popup && popupData && (
        <Popup
          module={popupData}
          template={pageContext?.page?.template}
          operatorStatus={pageContext?.page?.relation?.status}
        />
      )}
      <div className={`${styles.floatingArea} ${showScroll ? styles.show : ''}`}>
        <ScrollToTop />
        {OperatorBanner && (
          <OperatorBanner
            type={relation_type}
            template={template}
            sticky
            logo={pageContext.page.relation.logo_url}
            operator={pageContext.page.relation}
            closedBanner={closedBanner}
            setClosedBanner={setClosedBanner}
          />
        )}
        {Cookie && (
          <Cookie
            market={pageContext?.page?.market}
            type={relation_type}
            template={template}
            settingsCookie
            isPageHomepage={isPageHomepage}
          >
            <p>
              We use cookies in order to optimise our site and improve your experience with us. By
              using the site you consent to our
              <a href="/cookies" className="cookie-consent-gtm">
                Cookie Policy
              </a>
              .
            </p>
          </Cookie>
        )}
      </div>
    </>
  );
}

Body.propTypes = {
  pageContext: PropTypes.shape({
    siteName: PropTypes.string,
    allMarkets: PropTypes.shape({}),
    page: PropTypes.shape({
      id: PropTypes.number,
      relation_type: PropTypes.string,
      path: PropTypes.string,
      template: PropTypes.string,
      relation: PropTypes.shape({
        status: PropTypes.string,
        logo_url: PropTypes.string,
      }),
      market: PropTypes.string,
    }),
    marketSections: PropTypes.shape({
      footer_navigation: PropTypes.shape({}),
      popup: PropTypes.shape({
        modules: PropTypes.arrayOf({}),
      }),
    }),
  }).isRequired,
  excludeTemplateInPopup: PropTypes.arrayOf(PropTypes.string),
  offsetTop: PropTypes.number,
  children: PropTypes.element,
  hideOperatorBanner: PropTypes.bool,
};

export default Body;
