import React, { lazy, Suspense } from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import PropTypes from 'prop-types';
// eslint-disable-next-line import/no-extraneous-dependencies
import { getURLParam } from 'gatsby-core-theme/src/helpers/getters';
import Module from 'gatsby-core-theme/src/components/molecules/module';

import keygen from 'gatsby-core-theme/src/helpers/keygen';
import settings from 'gatsby-core-theme/src/constants/settings.mjs';
import NotFound from 'gatsby-core-theme/src/components/atoms/not-found';
import FeedBackModule from '../../../../components/atoms/feedBackModule';
import AuthorBox from '~atoms/author-box';
import { isSearchPath } from '~helpers/isSearchPath';
import useTranslate from '~hooks/useTranslate/useTranslate';
import styles from './main.module.scss';

const Main = ({
  section = {},
  pageContext = {},
  serverData = {},
  showAuthor = true,
  showAtomsAuthor = true,
  exclOperator = false,
  exclFeedback = false,
  exclNewsletter = false,
  isStickyNewsletter = false,
  forceAuthorBox = false
}) => {

  const { page, allMarkets } = pageContext;
  const siteName = process.env.GATSBY_SITE_NAME;
  const showNewsletter =
    !(
      settings.newsletter[siteName]?.filter_pages?.includes('*') ||
      settings.newsletter[siteName]?.filter_pages?.includes(page?.relation_type) ||
      settings.newsletter.default?.filter_pages?.includes(page?.relation_type) ||
      exclNewsletter
    ) && !process.env.HIDE_NEWSLETTER;

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

  const pathPrefixes = isSearchPath(allMarkets, page.path) || page.template === 'search';
  const SearchPage = pathPrefixes ? lazy(() => import(`~pages/search`)) : null;
  const HtmlSitemap = pageContext.sitemapData
    ? lazy(() => import(`gatsby-core-theme/src/components/atoms/sitemap`))
    : null;

  const Newsletter = showNewsletter
    ? lazy(() => import('gatsby-core-theme/src/components/molecules/newsletter'))
    : null;
  const NewsletterSuccess =
    showNewsletter && typeof window !== 'undefined' && Boolean(getURLParam('subscribed'))
      ? lazy(() => import(`gatsby-core-theme/src/components/molecules/newsletter/success`))
      : null;

  const EEAT =
    process.env.GATSBY_SITE_NAME === 'irishluck.ie' ||
    process.env.GATSBY_SITE_NAME === 'demosite' ||
    process.env.GATSBY_SITE_NAME === 'playcasino.co.za' || 
    process.env.GATSBY_SITE_NAME === 'superbonusschweiz.com' ||
    process.env.GATSBY_SITE_NAME === 'casinon.com';

  const showAuthorBox = page.author && page.author_id && !isContactUsPage && !page?.allAuthors;
  const sitemapTranslation = useTranslate('sitemap', 'sitemap');

  const ReviewCredits =
    page.path !== '/' &&
    !isContactUsPage &&
    page.path !== 'news' &&
    page.path !== sitemapTranslation &&
    page.template !== 'ppc' &&
    page.author_id &&
    showAuthor
      ? lazy(() => import('../../../../components/atoms/review-credits'))
      : null;

  const Author =
    page.path !== '/' &&
    !isContactUsPage &&
    page.path !== 'news' &&
    page.path !== sitemapTranslation &&
    page.template !== 'ppc' &&
    page.author_id &&
    showAtomsAuthor &&
    showAuthor 
      ? lazy(() => import('~atoms/author'))
      : null;

  const Disquss =
    page.type === 'operator' && process.env.ENABLE_DISQUSS === 'true'
      ? lazy(() => import(`~atoms/disquss`))
      : null;

  const Feedback =
    page?.sections?.main?.feedbackCounter &&
    !isContactUsPage &&
    !exclFeedback &&
    lazy(() => import(`../../../../components/atoms/feedback`));

  const date =
    page.manual_updated_date || page.manual_published_date
      ? page.manual_updated_date || page.manual_published_date
      : '';

  return (
    <main className={`${styles?.modulePage || ''} ${styles[page?.template] || ''}`}>
      {page.path.includes('404') && <NotFound pageContext={pageContext} />}
      {HtmlSitemap && (
        <Suspense fallback={<></>}>
          <HtmlSitemap pageContext={pageContext} />
        </Suspense>
      )}

      {EEAT
        ? ReviewCredits && (
            <Suspense fallback={<></>}>
              <ReviewCredits
                date={date}
                authors={page?.allAuthors ? page?.allAuthors : page?.author_id && [page?.author]}
                readingTime={page.reading_time}
                reviewer={page.reviewer_id && page?.reviewer}
                hasAuthorBox={Boolean(AuthorBox)}
                type={page?.template}
              />
            </Suspense>
          )
        : Author && (
            <Suspense fallback={<></>}>
              <Author
                name={page.author?.name}
                date={date}
                type={page?.template}
                authorImg={page?.author?.image}
                readingTime={page.reading_time}
                link={page?.author?.profile_page_path}
                reviewer={page.reviewer_id && page?.reviewer}
                hasAuthorBox={Boolean(AuthorBox)}
                headerOffset={174}
              />
            </Suspense>
          )}

      {section &&
        section.modules &&
        section.modules.map((module, index) => (
          <Module
            key={keygen()}
            module={module}
            page={page}
            pageContext={pageContext}
            serverData={serverData}
            index={index}
            exclOperator={exclOperator}
            modulePosition={index + 1}
          />
        ))}

      {Disquss && (
        <Suspense fallback={<></>}>
          <Disquss page={pageContext.page} />
        </Suspense>
      )}

      {SearchPage && (
        <Suspense fallback={<div className={styles.searchContainer} />}>
          <SearchPage page={page} serverData={serverData}  pageContext={pageContext} allMarkets={pageContext.allMarkets} />
        </Suspense>
      )}
      {(showAuthorBox || forceAuthorBox) && (
        <Suspense fallback={<></>}>
          <AuthorBox
            author={page.author}
            page={page}
            date={date}
            readingTime={page.reading_time}
            reviewer={page.reviewer_id && page?.reviewer}
          />
        </Suspense>
      )}
      {Feedback && (
        <Suspense fallback={<></>}>
          <Feedback
            trueVotes={page?.true_votes}
            falseVotes={page?.false_votes}
            pageId={page?.id}
            casinoTitle={page?.relation ? page?.relation.name : page?.title}
            operatorImg={page?.relation?.logo}
            type={page?.type}
          />
        </Suspense>
      )}
      {Newsletter && (
        <Suspense fallback={<></>}>
          <Newsletter page={page} isSticky={isStickyNewsletter} />
        </Suspense>
      )}
      {NewsletterSuccess && <NewsletterSuccess />}
      {page.template !== 'ppc' && Feedback && (
        <Suspense fallback={<></>}>
          <FeedBackModule />
        </Suspense>
      )}
    </main>
  );
};

Main.propTypes = {
  exclOperator: PropTypes.bool,
  exclFeedback: PropTypes.bool,
  exclNewsletter: PropTypes.bool,
  section: PropTypes.shape({
    modules: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string,
      })
    ),
  }),
  page: PropTypes.shape({
    path: PropTypes.string,
  }),
  pageContext: PropTypes.shape({}),
  showAuthor: PropTypes.bool,
  showAtomsAuthor: PropTypes.bool,
  serverData: PropTypes.shape({}),
  isStickyNewsletter: PropTypes.bool,
  forceAuthorBox: PropTypes.bool
};

export default Main;
