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 styles from 'gatsby-core-theme/src/components/molecules/main/main.module.scss';
import settings from 'gatsby-core-theme/src/constants/settings.mjs';
import FeedBackModule from '../../../../components/atoms/feedBackModule';
import ReviewCredits from '../../../../components/atoms/review-credits';
import Author from '~atoms/author';
import { isSearchPath } from '~helpers/isSearchPath';

const Main = ({
  section = {},
  pageContext = {},
  serverData = {},
  showAuthor = true,
  exclOperator = false,
  exclFeedback = false,
  exclNewsletter = 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);
  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 NotFound = page.path.includes('404')
    ? lazy(() => import(`gatsby-core-theme/src/components/atoms/not-found`))
    : null;

  const AuthorBox =
    page.author && page.author_id && !isContactUsPage
      ? lazy(() => import(`~atoms/author-box`))
      : null;

  const showReviewCredits =
    page.path !== '/' &&
    !isContactUsPage &&
    page.path !== 'news' &&
    page.path !== 'sitemap' &&
    page.template !== 'ppc' &&
    page.author_id &&
    showAuthor;

  const showAuthorComponent =
    page.path !== '/' &&
    !isContactUsPage &&
    page.path !== 'news' &&
    page.path !== 'sitemap' &&
    page.template !== 'ppc' &&
    page.author_id &&
    showAuthor;

  const useReviewCredits =
    process.env.GATSBY_SITE_NAME === 'irishluck.ie' ||
    process.env.GATSBY_SITE_NAME === 'demosite' ||
    process.env.GATSBY_SITE_NAME === 'playcasino.co.za';

  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] || ''}`}>
      {NotFound && (
        <Suspense fallback={<></>}>
          <NotFound pageContext={pageContext} />
        </Suspense>
      )}
      {HtmlSitemap && (
        <Suspense fallback={<></>}>
          <HtmlSitemap pageContext={pageContext} />
        </Suspense>
      )}

      {useReviewCredits
        ? showReviewCredits && (
            <ReviewCredits
              date={date}
              author={page?.author_id && page?.author}
              readingTime={page.reading_time}
              reviewer={page.reviewer_id && page?.reviewer}
              hasAuthorBox={Boolean(AuthorBox)}
              type={page?.template}
            />
          )
        : showAuthorComponent && (
            <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}
            />
          )}

      {section.modules &&
        section.modules.map((module, index) => (
          <Module
            key={keygen()}
            module={module}
            page={page}
            pageContext={pageContext}
            serverData={serverData}
            index={index}
            exclOperator={exclOperator}
            modulePosition={index}
          />
        ))}
      {SearchPage && (
        <Suspense fallback={<></>}>
          <SearchPage page={page} />
        </Suspense>
      )}
      {AuthorBox && (
        <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?.standardised_logo_url || page?.relation?.logo_url}
          />
        </Suspense>
      )}
      {Newsletter && (
        <Suspense fallback={<></>}>
          <Newsletter page={page} />
        </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,
  serverData: PropTypes.shape({}),
};

export default Main;
