/* 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 { v4 as uuidv4 } from 'uuid';
import { getSection, getMarketSection } 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 OpenGraph from 'gatsby-core-theme/src/components/atoms/open-graph';
import { pageTypes } from 'gatsby-core-theme/src/constants/site-settings/navigation';
import Popup from '../../../../components/organisms/popup';
import LinkMenu from '../../../../components/atoms/link-menu';
import { isSearchPath } from '~helpers/isSearchPath';
import ExclusiveOperator from '../../../../components/molecules/operator-exclusive';
import StickyOperatorBanner from '../../../../components/molecules/stickyOperatorBanner';
import { setCookie, getCookie } from '~helpers/cookies';

function Body({ pageContext, children, serverData }) {
  useEffect(() => {
    if (!getCookie('affUUID')) {
      setCookie('affUUID', uuidv4());
    }
  }, []);

  const getBodySection = (name) => getSection(name, pageContext);
  const { template } = pageContext.page;

  const main = getBodySection('main');

  const navigation = getMarketSection(
    pageTypes[template]?.section || pageTypes.default.section,
    pageContext
  );

  const stickyOperatorBanner = getMarketSection(
    pageTypes[template]?.operatorBannerSection || pageTypes.default.operatorBannerSection,
    pageContext
  );

  
  const footer = pageTypes[template]?.disableFooter
    ? null
    : getMarketSection('footer', pageContext);

  const links = pageTypes[template]?.disableFooter || pageTypes[template]?.disableFooterLinks ? null : getMarketSection('links', pageContext);

  const isHomePage = pageContext?.page && pageContext?.page.path === '/';
  const isPPC = pageContext?.page && pageContext?.page?.template === 'ppc';
  const pageType = pageContext.page.relation_type;
  const is404 = pageContext.page.path.includes('404');

  const excOperator = navigation?.modules.find((module) => module.name === 'bonus');

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

  const showOpenGraph = process.env.ENABLE_OPENGRAPH === 'true' && !isHomePage;

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

  const customComponent = pageTypes[template]?.customComponent ?? pageTypes.default.customComponent;
  const excludeFooterFromBody = pageTypes[template]?.excludeFooterFromBody ?? pageTypes.default?.excludeFooterFromBody

  const menu = pageTypes[template]?.navMenu ?? pageTypes.default.navMenu;
  const disableSearch = pageTypes[template]?.disableSearch ?? pageTypes.default.disableSearch;
  const exclusiveOperator =
    pageTypes[template]?.exclusiveOperator ?? pageTypes.default.exclusiveOperator;

  const stickyOperator = pageTypes[template]?.stickyOperatorBanner ?? pageTypes.default.stickyOperatorBanner;
    
  const disablePopup = pageTypes[template]?.disablePopup ?? pageTypes.default.disablePopup;

  const showExclusiveOperator = excOperator && pageType !== 'operator' && exclusiveOperator;

  const showStickyOperatorBanner =
    toplistInStickyBanner && pageType !== 'operator' && stickyOperator;

  const popupData = pageContext?.marketSections?.popup?.modules?.find((m) => m.name === 'top_list');

  const popupImage = pageContext?.marketSections?.popup?.extra_fields?.popup_image;  

  return (
    <>
      {navigation && (
        <Navigation
          template={template}
          pageContext={pageContext}
          section={navigation}
          disableSearch={disableSearch}
          hasCustomComponent={customComponent}
          menu={menu}
          options={{
            mobile: {
              animation: 'collapseFull',
              closeHandler: null,
              stopScrollOnOpen: true,
              canOpenAllSubMenus: true,
              subMenuDropDownButton: true,
            },
            desktop: {
              orientation: 'horizontal',
            },
          }}
        />
      )}
      {!isSearch && !is404 && <Header exclOperator={showExclusiveOperator} section={pageContext} />}
      {showExclusiveOperator && (
        <ExclusiveOperator bonus={excOperator} template={pageContext?.page?.template} />
      )}
      {!children && (
        <Main
          exclOperator={showExclusiveOperator}
          section={main}
          pageContext={pageContext}
          serverData={serverData}
        />
      )}

      {children && <main>{children}</main>}

      {!isPPC && links && !isContactUsPage && (
        <aside>
          <LinkMenu section={links} template={template} />
        </aside>
      )}
      {showOpenGraph && <OpenGraph text="Del på" page={pageContext?.page} />}
      {footer && !excludeFooterFromBody && (
        <Footer
          section={footer}
          template={template}
          page={pageContext}
          footerTemplate={footer.style || 'template_one'}
          dmcaImage="../../../../../../images/dmca.png"
        />
      )}
      {!disablePopup && pageContext?.marketSections?.popup && popupData && (
        <Popup
          module={popupData}
          template={pageContext?.page?.template}
          operatorStatus={pageContext?.page?.relation?.status}
          image={popupImage}
        />
      )}
      {showStickyOperatorBanner && (
        <StickyOperatorBanner data={stickyOperatorBanner} template={template} />
      )}

      <FloatingArea pageContext={pageContext} template={template} />
    </>
  );
}

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

export default Body;
