import React from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import PropTypes from 'prop-types';
// eslint-disable-next-line import/no-extraneous-dependencies
import loadable from '@loadable/component';
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 '../../../../constants/settings/newsletter';
import FeedBackModule from '../../../../components/atoms/feedBackModule';
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[siteName]?.filter_pages?.includes('*') ||
    settings[siteName]?.filter_pages?.includes(page?.relation_type) ||
    settings.default?.filter_pages?.includes(page?.relation_type) ||
    exclNewsletter
  );
  const isContactUsPage = !!section?.modules?.filter((module) => module.name === 'contact_form')
    .length;

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

  const Newsletter = showNewsletter
    ? loadable(() => import('../../../../components/molecules/newsletter'))
    : null;
  const NewsletterSuccess =
    showNewsletter && typeof window !== 'undefined' && Boolean(getURLParam('subscribed'))
      ? loadable(() => import(`../../../../components/atoms/newsletter/success`))
      : null;
  const NotFound = page.path.includes('404')
    ? loadable(() => import(`gatsby-core-theme/src/components/atoms/not-found`))
    : null;
  const AuthorBox =
    page.author_id && !isContactUsPage ? loadable(() => import(`~atoms/author-box`)) : null;
  const Author =
    page.path !== '/' &&
    !isContactUsPage &&
    page.path !== 'news' &&
    page.path !== 'sitemap' &&
    page.template !== 'ppc' &&
    page.author &&
    showAuthor
      ? loadable(() => import('~atoms/author'))
      : null;
  const Feedback =
    page?.sections?.main?.feedbackCounter &&
    !isContactUsPage &&
    !exclFeedback &&
    loadable(() => 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 && <NotFound pageContext={pageContext} />}
      {HtmlSitemap && <HtmlSitemap pageContext={pageContext} />}
      {Author && (
        <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 && <SearchPage page={page} />}
      {AuthorBox && (
        <AuthorBox
          author={page.author}
          page={page}
          date={date}
          readingTime={page.reading_time}
          reviewer={page.reviewer_id && page?.reviewer}
        />
      )}
      {Feedback && (
        <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}
        />
      )}
      {Newsletter && <Newsletter page={page} />}
      {NewsletterSuccess && <NewsletterSuccess />}
      {page.template !== 'ppc' && Feedback && <FeedBackModule />}
    </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;
