/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/prop-types */
import React, { Suspense, useContext } from 'react';
import PropTypes from 'prop-types';
import { mainSettings } from 'gatsby-core-theme/src/constants/site-settings/main';
import Content from 'gatsby-core-theme/src/components/molecules/content';
import { Context } from '~context/MainProvider.js';
import ModuleTitle from '../../atoms/module-title';
import AdminButton from '~atoms/admin/button';
import { resolveModule } from './module-registry';

import styles from './module.module.scss';

const Modules = ({ module, pageContext, index, exclOperator, serverData, modulePosition }) => {
  const { page } = pageContext;
  const { siteSchema } = page || {};
  const { admin } = useContext(Context) || {};
  const socialIcons =
    siteSchema &&
    (({ instagram, facebook, twitter, linkedin, youtube }) => ({
      instagram,
      facebook,
      twitter,
      linkedin,
      youtube,
    }))(siteSchema);

  const isContactUsPage = !!page?.sections?.main?.modules?.filter(
    (each) => each.name === 'contact_form'
  ).length;

  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 === 'casinon.com';

  const anchorLabel = (() => {
    const hideArchiveLabel = process.env.HIDE_ARCHIVE_LABEL === 'true';

    if (module.name === 'archive') {
      return hideArchiveLabel ? null : 'archiveLabel';
    }

    return module?.anchor_slug || undefined;
  })();

  const resolved = resolveModule(module.name, {
    module,
    page,
    pageContext,
    serverData,
    socialIcons,
    EEAT,
    isContactUsPage,
    anchorLabel,
  });

  const homepageFirstModule = index === 0 && page.path === '/';
  const moduleClassName = `${module.name}Module`;

  const moduleBackgroundColor = {
    '--module-background-color': module.background_color,
  };

  const fontColor = {};
  if (mainSettings?.colors) {
    if (
      module.background_color?.toLowerCase() ===
      mainSettings.colors.primary.background.toLowerCase()
    ) {
      fontColor['--module-font-color'] = mainSettings.colors.primary.text;
      fontColor['--module-font-color-link'] = mainSettings.colors.primary.link;
    } else if (
      module.background_color?.toLowerCase() ===
      mainSettings.colors.secondary.background.toLowerCase()
    ) {
      fontColor['--module-font-color'] = mainSettings.colors.secondary.text.toLowerCase();
      fontColor['--module-font-color-link'] = mainSettings.colors.secondary.link;
    }
  }

  const style = {};
  Object.assign(style, moduleBackgroundColor, fontColor);

  const showModuleIntro =
    module.name !== 'top_list' &&
    module.module_introduction &&
    module.module_introduction !== '<p></p>';

  if (!resolved) {
    return null;
  }

  const { Component: ModuleComponent, props: moduleProps, meta } = resolved;
  const { hideModuleHeader, suspense, sportstakeSuspense } = meta;

  const moduleBody = (
    <ModuleComponent
      module={module}
      page={page}
      pageContext={pageContext}
      noModuleIntro={!showModuleIntro}
      {...moduleProps}
      exclOperator={exclOperator}
      isHomepageFirstModule={homepageFirstModule}
      modulePosition={modulePosition}
    />
  );

  return (
    <div
      data-track={!!module.anchor_label}
      id={
        module.name === 'archive' && (module.module_title || module.module_title)
          ? null
          : anchorLabel
      }
      style={module.background_color && style}
      className={`${styles[moduleClassName] !== undefined ? styles[moduleClassName] || '' : ''} ${
        module?.name || ''
      } ${showModuleIntro ? '' : styles.noModuleIntro}
        ${!showModuleIntro && module.name !== 'cards_v2' ? styles.noModuleIntroCards : ''} 
        ${styles?.module || ''} ${module?.style ? styles[module.style] || '' : ''} module ${
        homepageFirstModule ? styles?.isHomepageFirstModule || '' : ''
      }`}
    >
      {!hideModuleHeader && (
        <>
          {module.name !== 'top_list' && (
            <ModuleTitle
              module={module}
              isHomepageFirstModule={homepageFirstModule}
              anchorLabel={module.name === 'archive' ? anchorLabel : null}
            />
          )}
          {showModuleIntro && (
            <Content
              isModuleIntroduction={module.module_introduction}
              module={{ value: module.module_introduction }}
              isHomepageFirstModule={homepageFirstModule}
              pageTemplate={page?.template}
              modulePosition={modulePosition}
            />
          )}
        </>
      )}
      {suspense ? (
        <Suspense
          fallback={
            <div
              className={`${
                sportstakeSuspense ? styles.sportstake : styles[module.name]
              } ${
                styles[`${moduleClassName}_suspense`] !== undefined
                  ? styles[`${moduleClassName}_suspense`] || ''
                  : ''
              }`}
            />
          }
        >
          {moduleBody}
        </Suspense>
      ) : (
        moduleBody
      )}
      {admin && <AdminButton page={page} module={module} modulePosition={modulePosition - 1} />}
    </div>
  );
};

Modules.propTypes = {
  exclOperator: PropTypes.bool,
  module: PropTypes.shape({
    anchor_label: PropTypes.string,
    name: PropTypes.string,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
    module_title_tag: PropTypes.string,
    module_title: PropTypes.string,
    link_label: PropTypes.string,
    link_value: PropTypes.string,
    style: PropTypes.string,
  }),
  page: PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }),
  pageContext: PropTypes.shape({}),
};

export default Modules;
