/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import { getURLParam } from 'gatsby-core-theme/src/helpers/getters';
import Module from '~molecules/module';
import settings from '../../../../constants/newsletter';
import styles from './main.module.scss';
import keygen from '~helpers/keygen';

const Main = ({ section = {}, pageContext = {}, serverData = {}, exclOperator = false }) => {
  const { page } = pageContext;
  const SearchPage = page.path === 's' ? loadable(() => import(`~pages/search`)) : null;
  const HtmlSitemap = page.path === 'sitemap' ? loadable(() => import(`~atoms/sitemap`)) : null;
  const AuthorBox = page.author_id ? loadable(() => import(`~atoms/author-box`)) : null;
  const NotFound = page?.path?.includes('404') ? loadable(() => import(`~atoms/not-found`)) : null;

  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)
  );

  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;

  return (
    <main className={`${styles.modulePage} ${styles.main} ${styles[page.template]}`}>
      {NotFound && <NotFound />}
      {HtmlSitemap && <HtmlSitemap pageContext={pageContext} />}
      {section.modules &&
        section.modules.map((module) => (
          <Module
            key={keygen()}
            module={module}
            exclOperator={exclOperator}
            page={page}
            pageContext={pageContext}
            serverData={serverData}
          />
        ))}
      {AuthorBox && (
        <AuthorBox
          author={page.author}
          date={page.updated_at ? page.updated_at : page.created_at}
          readingTime={page.reading_time}
          reviewer={page.reviewer_id && page.reviewer}
        />
      )}
      {SearchPage && <SearchPage page={page} />}
      {Newsletter && <Newsletter page={page} />}
      {NewsletterSuccess && <NewsletterSuccess />}
    </main>
  );
};

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

export default Main;
