import React from "react";
import { get, has } from "lodash";
import WebFontLoader from "webfontloader";
import LoadingBar from "react-top-loading-bar";

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";

import { Page } from "./Page";
// import Test from "./Test";
import { PageScripts } from "./addons";

import reducers from "./reducers";

// import externalContent from "./data/content.json";
import { IContent } from "./types";

const Site: React.FC = () => {
  const [content, setContent] = React.useState<IContent[]>([]);
  const [trackingScripts, setTrackingScripts] = React.useState("{}");
  const [fontList, setFontList] = React.useState<string[]>([]);

  const fetchContent = async () => {
    const host =
      process.env.REACT_APP_SERVER_ENDPOINT === "localhost"
        ? `sandcastlesites.s3-website-us-east-1.amazonaws.com/qa-test-01.tenminutefunnels.com`
        : window.location.hostname;

    const protocol = window.location.protocol;
    const url = `${protocol}//${host}/content.json`;
    const response = await fetch(url, {
      method: "GET",
      mode: "cors",
      cache: "no-cache",
      headers: {
        "Content-Type": "application/json",
        Origin: window.location.origin,
      },
    });
    const result = await response.json();
    const pages = get(result, "pages", "[]");
    const scripts = JSON.parse(unescape(get(result, "scripts", "{}")));
    const fonts = get(result, "fonts", []);

    // console.log({ pages, scripts, fonts });
    setContent(pages);
    setTrackingScripts(scripts);
    setFontList(fonts);
  };

  React.useEffect(() => {
    fetchContent();
    // console.log("page switch");
  }, []);

  WebFontLoader.load({
    google: {
      families: ["Roboto:300,400,500,700", "Material Icons", ...fontList],
    },
  });

  return (
    <Provider store={createStore(reducers)}>
      <Router>
        {content.length ? (
          <Switch>
            {/* Create Home Page */}
            {content
              .filter(({ isHomePage }) => isHomePage)
              .map((page, key) => (
                <Route
                  key={key}
                  exact
                  path="/"
                  render={() => <Page {...page} />}
                />
              ))}

            {/* Create All Pages */}
            {content.map((page, key) => (
              <Route
                key={key}
                exact
                path={`/${page.slug}`}
                render={() => <Page {...page} />}
              />
            ))}
            {/* Create 404 Page */}
            {content
              .filter(({ is404 }) => is404)
              .map((page, key) => (
                <Route key={key} render={() => <Page {...page} />} />
              ))}

            {(has(trackingScripts, "head") ||
              has(trackingScripts, "body") ||
              has(trackingScripts, "bodyEnd")) && (
              <PageScripts alreadyParsed trackingPayload={trackingScripts} />
            )}
          </Switch>
        ) : (
          <LoadingBar progress={100} height={3} color="gray" />
        )}
      </Router>
    </Provider>
  );
};

export default Site;
