/* eslint-disable camelcase */
/* eslint-disable no-useless-concat */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useEffect } 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 Main from 'gatsby-core-theme/src/components/molecules/main';
import Header from 'gatsby-core-theme/src/components/molecules/header';
import FloatingArea from 'gatsby-core-theme/src/components/molecules/floating-area';
import Footer from 'gatsby-core-theme/src/components/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 = [], serverData }) {
  useEffect(() => {
    if (!getCookie('affUUID')) {
      setCookie('affUUID', uuidv4());
    }
  }, []);

  const getBodySection = (name) => getSection(name, pageContext);

  const main = getBodySection('main');
  const navigation = getBodySection('navigation');
  const footer = getBodySection('footer');

  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 { template } = 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 && footerNavigationData?.modules?.length > 0 && pageType !== 'operator'
      ? loadable(() => import(`../../../../components/organisms/footer-navigation`))
      : null;

  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}
          serverData={serverData}
        />
      )}
      {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}
          hasFooterLinks={FooterNavigation !== null}
          footerTemplate={footer.style || 'template_one'}
          dmcaImage="../../../../../../images/dmca.png"
        />
      )}
      <FloatingArea
        pageContext={pageContext}
        template={template}
        customStyles={styles}
        isPageHomepage={isHomePage}
      />
      {!excludeTemplateInPopup.includes(pageContext?.page?.template) && Popup && popupData && (
        <Popup
          module={popupData}
          template={pageContext?.page?.template}
          operatorStatus={pageContext?.page?.relation?.status}
        />
      )}
    </>
  );
}

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),
  children: PropTypes.element,
  serverData: PropTypes.shape({}),
};

export default Body;
