/* eslint-disable react/prop-types */
/* eslint-disable react/forbid-prop-types */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import MainProvider from '~context/MainProvider';
import Body from '~pages/body';
import HeadData from '~organisms/head';

const App = ({ pageContext }) => {
  const { translations = {}, isTracker, isTrackeGeo, isPreview } = pageContext;
  const [previewContext, setPreviewContext] = useState({});
  const [isLoading, setIsLoading] = useState({});

  async function getData(searchParams, staticPath = null) {
    const { getPreview } = await import('~helpers/api');
    getPreview(
      pageContext.siteName,
      !staticPath ? searchParams.get('path') || '/' : staticPath,
      searchParams.get('market_id'),
      pageContext
    ).then((previewResponse) => {
      if (previewResponse.page) {
        // siteInfo and siteSchema are added to page for schemaGenerator()
        previewResponse.page.siteInfo = pageContext.siteInfo;
        previewResponse.page.siteSchema = pageContext.siteSchema;
      }
      setPreviewContext(previewResponse);
      setIsLoading(false);
    });
  }

  useEffect(() => {
    if (isPreview) {
      setIsLoading(true);
      const searchParams =
        typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
      if (!searchParams.get('path')) {
        window.location = `${window.location.origin}/preview?path=/`;
      }
      getData(searchParams);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (isPreview) {
    if (isLoading) {
      return 'Loading...';
    }
  }

  const TrackerContent = isTracker ? loadable(() => import(`~pages/tracker`)) : null;
  const TrackerGeoContent = isTrackeGeo ? loadable(() => import(`~pages/tracker-geo`)) : null;

  if (TrackerGeoContent) {
    return (
      <>
        <TrackerGeoContent pageContext={pageContext} path={pageContext.page.path} />
      </>
    );
  }

  return isTracker ? (
    <>
      <TrackerContent pageContext={pageContext} path={pageContext.page.path} />
    </>
  ) : (
    <MainProvider value={{ translations }}>
      <div
        dir={
          (isPreview ? previewContext.page?.language === 'ar' : pageContext.page?.language === 'ar')
            ? 'rtl'
            : 'ltr'
        }
        id="container-modules"
      >
        <Body pageContext={isPreview ? previewContext : pageContext} />
      </div>
    </MainProvider>
  );
};

export const Head = ({ pageContext }) => (
  <HeadData page={pageContext.page} siteInfo={pageContext.siteInfo} />
);

App.propTypes = {
  pageContext: PropTypes.shape({
    siteName: PropTypes.string,
    isTracker: PropTypes.bool,
    isPreview: PropTypes.bool,
    page: PropTypes.shape({
      id: PropTypes.number,
      path: PropTypes.string,
    }),
    translations: PropTypes.object,
    siteInfo: PropTypes.shape({
      robots_txt: PropTypes.string,
      site_logo: PropTypes.string,
      site_name: PropTypes.string,
    }),
    siteSchema: PropTypes.shape({
      site_name: PropTypes.string,
    }),
  }),
};

export default App;
