/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { globalHistory } from '@reach/router';

// import Body from '~pages/body';
// import Head from '~organisms/head';
// import { getPreview } from '~helpers/api';

const AppPreview = ({ 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,
      pageContext
    ).then((previewResponse) => {
      setPreviewContext(previewResponse);
      setIsLoading(false);
    });
  }

  useEffect(() => {
    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);
    // let { hi, bye } = await import('./say.js');
    // getPreview(pageContext.siteName, searchParams.get('path') || '/', pageContext).then(
    //   (previewResponse) => {
    //     setPreviewContext(previewResponse);
    //     setIsLoading(false);
    //   }
    // );

    globalHistory.listen(({ location }) => {
      setIsLoading(true);

      getData(null, location.search.replace('?path=', ''));
      // getPreview(pageContext.siteName, location.search.replace('?path=', ''), pageContext)
      //   .then((previewResponse) => {
      //     setPreviewContext(previewResponse);
      //     setIsLoading(false);
      //   })
      //   .catch(() => {
      //     alert('failed to load..');
      //   });
    });
    // eslint-disable-next-line
  }, [pageContext.siteName]);

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

  return (
    <>
      {/* <Head page={previewContext.page} siteInfo={previewContext.siteInfo} />
      <Body pageContext={previewContext} /> */}
    </>
  );
};

AppPreview.propTypes = {
  pageContext: PropTypes.shape({
    page: PropTypes.shape({
      id: PropTypes.number,
    }),
    siteName: PropTypes.string,
    siteInfo: PropTypes.shape({
      robots_txt: PropTypes.string,
      site_logo: PropTypes.string,
      site_name: PropTypes.string,
    }),
  }),
};

export default AppPreview;
