import React from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import Module from '~molecules/module';
import styles from './main.module.scss';
import keygen from '~helpers/keygen';
import { isSearchPath } from '~helpers/isSearchPath';

const Main = ({ section = {}, pageContext = {}, serverData = {}, exclOperator = false }) => {
  const { page, allMarkets } = pageContext;

  const pathPrefixes = isSearchPath(allMarkets, page.path);

  const SearchPage = pathPrefixes ? loadable(() => import(`~pages/search`)) : null;
  const HtmlSitemap = pageContext.sitemapData ? 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;

  return (
    <main className={styles.modulePage || ''}>
      {NotFound && <NotFound pageContext={pageContext} />}
      {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} />}
    </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;
