/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import { anchorLink } from 'gatsby-core-theme/src/helpers/strings';
import { prettyTracker, getSectionExtraField } from 'gatsby-core-theme/src/helpers/getters';
import ModuleTitle from '../../atoms/module-title';
import { removeSymbols } from '../../../../helpers/strings';

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

const Modules = ({ module, pageContext, index, exclOperator }) => {
  const { page } = pageContext;
  const { siteSchema } = page || {};

  const socialIcons =
    siteSchema &&
    (({ instagram, facebook, twitter, linkedin, youtube }) => ({
      instagram,
      facebook,
      twitter,
      linkedin,
      youtube,
    }))(siteSchema);

  const GetModuleComponent = (moduleItem) => {
    const { items, name, style } = moduleItem || {};

    switch (name) {
      // Modules
      case 'content':
        return loadable(() => import('gatsby-core-theme/src/components/molecules/content'));
      case 'top_list':
        return loadable(() => import('gatsby-core-theme/src/components/organisms/toplist'));
      case 'archive':
        if (!items || items.length === 0) return null;
        return loadable(() => import('gatsby-core-theme/src/components/organisms/archive'));
      case 'counter':
        return loadable(() => import('gatsby-core-theme/src/components/molecules/counter'));
      case 'contact_form':
        return loadable(() => import('gatsby-core-theme/src/components/atoms/contact-form'));
      case 'cards':
        return loadable(() => import('../../../../components/organisms/cards'));
      case 'cards_v2':
        return loadable(() => import('../../../../components/organisms/cards'));
      case 'pros_and_cons':
        return loadable(() => import('gatsby-core-theme/src/components/molecules/pros-cons'));
      case 'accordion':
        return loadable(() => import('gatsby-core-theme/src/components/organisms/accordion'));
      case 'anchor':
        if (items && items.length > 0) {
          if (style === 'template_two') {
            return loadable(() =>
              import('gatsby-core-theme/src/components/organisms/anchor/template-two')
            );
          }
          return loadable(() =>
            import('gatsby-core-theme/src/components/organisms/anchor/template-one')
          );
        }
        return null;
      case 'carousel':
        if (
          items.length > 0 && // has items
          items.filter((item) => item.image === null).length === 0 // not filled with null items
        ) {
          return loadable(() => import('gatsby-core-theme/src/components/organisms/carousel'));
        }
        return null;
      case 'bonus':
        return loadable(() =>
          import('gatsby-core-theme/src/components/molecules/bonus/template-one')
        );
      case 'image':
        return loadable(() => import('gatsby-core-theme/src/components/atoms/image'));
      case 'spotlights':
        if (process.env.ENABLE_SPOTLIGHT_V2) {
          return loadable(() => import('~molecules/spotlights_v2'));
        }
        return loadable(() => import('~atoms/spotlights'));

      case 'faq':
        // eslint-disable-next-line react/destructuring-assignment
        if (moduleItem?.display_front_end === '1') {
          return loadable(() => import('../../../../components/molecules/faq'));
        }
        return null;
      // Template blocks
      case 'horse_racing_calculator':
        return loadable(() => import('../../../../components/molecules/horse-calculator'));
      case 'review_summary':
        return loadable(() => import('../../../../components/molecules/operator-summary'));
      case 'game_iframe':
      case 'iframe':
        if (moduleItem?.value_type === 'template_block') {
          return loadable(() => import('../../../../components/molecules/game-iframe'));
        }
        return loadable(() => import('gatsby-core-theme/src/components/atoms/iframe'));
      // Template blocks
      case 'info_grid':
      case 'information_grid':
        return loadable(() => import('../../../../components/atoms/info-grid/template-one'));
      case 'operator_information_block':
        if (getSectionExtraField(null, page, 'operator_is_placeholder') === '1') {
          return null;
        }
        return loadable(() => import('../../../../components/atoms/info-grid/template-two'));
      case 'content_box':
        return loadable(() => import('gatsby-core-theme/src/components/atoms/content-box'));
      case 'timeline':
        return loadable(() =>
          import('gatsby-core-theme/src/components/molecules/content-and-custom-module')
        );
      case 'welcome_bonus':
        return loadable(() => import('../../../../components/molecules/operator-welcome-bonus'));
      case 'score_gauges':
        return loadable(() => import('../../../../components/molecules/game-score-gauge'));
      case 'site_contacts':
        if (page?.siteSchema?.email === null) {
          return null;
        }
        return loadable(() => import('../../../../components/atoms/site-contacts'));
      case 'newsletter_optin':
        return loadable(() => import('../../../../components/molecules/newsletter-optin'));
      case 'wagering_calculator':
        return loadable(() => import('../../../../components/molecules/wagering-calculator'));
      case 'social_icons':
        return loadable(() => import('../../../../components/atoms/social-icons'));

      default:
        return null;
    }
  };

  const ModuleComponent = GetModuleComponent(module);

  const homepageFirstModule = index === 0 && page.path === '/';

  // eslint-disable-next-line no-nested-ternary
  const anchorLabel = module.anchor_label
    ? removeSymbols(anchorLink(module.anchor_label))
    : module.name === 'archive'
    ? 'archiveLabel'
    : null;

  const extraProps = () => {
    switch (module.name) {
      case 'bonus':
        return {
          operator: module?.value,
          logo: module?.value?.logo_url,
          hasLink: true,
          prettyLink: prettyTracker(module?.value, 'main', false, page?.template),
          isStickyCta: false,
        };
      case 'iframe':
        return {
          src: module?.iframe_source,
        };
      case 'social_icons':
        return Object.values(socialIcons).some((value) => value) ? { socialIcons } : {};

      default:
        return {
          anchorLabel,
        };
    }
  };

  const moduleClassName = `${module.name}Module`;

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

  const ModuleIntro =
    module.name !== 'top_list' &&
    module.module_introduction &&
    module.module_introduction !== '<p></p>' &&
    loadable(() => import('~molecules/content'));

  return (
    ModuleComponent && (
      <div
        id={
          module.name === 'archive' && (module.module_title || module.module_title)
            ? null
            : anchorLabel
        }
        style={module.background_color && moduleBackgroundColor}
        className={`${styles[moduleClassName] !== undefined ? styles[moduleClassName] || '' : ''} ${
          module?.name || ''
        } ${ModuleIntro ? '' : styles.noModuleIntro} ${styles?.module || ''} ${
          module?.style ? styles[module.style] || '' : ''
        } module ${homepageFirstModule ? styles?.isHomepageFirstModule || '' : ''}`}
      >
        {module.name !== 'cards_v2' && (
          <>
            {module.name !== 'top_list' && (
              <ModuleTitle
                module={module}
                isHomepageFirstModule={homepageFirstModule}
                anchorLabel={module.name === 'archive' && anchorLabel}
              />
            )}
            {ModuleIntro && (
              <ModuleIntro
                isModuleIntroduction={module.module_introduction}
                module={{ value: module.module_introduction }}
                isHomepageFirstModule={homepageFirstModule}
              />
            )}
          </>
        )}

        <ModuleComponent
          module={module}
          page={page}
          pageContext={pageContext}
          noModuleIntro={!ModuleIntro}
          {...extraProps()}
          exclOperator={exclOperator}
          isHomepageFirstModule={homepageFirstModule}
        />
      </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;
