import express from "express";
import path from "path";
import React from "react";
import { Provider } from "react-redux";
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import { Helmet } from "react-helmet";
import { ChunkExtractor, ChunkExtractorManager } from "@loadable/server";
import App from "../common/app";
import { AppState } from "../common/store";
import configureStore from "../common/store/configure";
import { queryClient } from "../common/core";
import { QueryClientProvider } from "@tanstack/react-query";

export const renderAmp = async (req: express.Request, state: AppState) => {
  const store = configureStore(state);

  const context = {};
  // This is the stats file generated by webpack loadable plugin
  const statsFile = path.resolve("./build/loadable-stats.json");
  // We create an extractor from the statsFile
  const extractor = new ChunkExtractor({ statsFile, entrypoints: ["client"] });

  let markup = renderToString(
    <ChunkExtractorManager extractor={extractor}>
      <Provider store={store}>
        <QueryClientProvider client={queryClient}>
          <StaticRouter location={req.originalUrl} context={context}>
            <App />
          </StaticRouter>
        </QueryClientProvider>
      </Provider>
    </ChunkExtractorManager>
  );

  const helmet = Helmet.renderStatic();
  const headHelmet = helmet.meta.toString() + helmet.title.toString() + helmet.link.toString();

  return `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="utf-8" />
                <meta name="theme-color" content="#000000"/>
                ${headHelmet}
                <link rel="icon" href="/favicon.png" />
                <link rel="apple-touch-icon" href="/logo192.png" />
                <link rel="manifest" href="/manifest.json" />
            </head>
            <body class="${`theme-${state.global.theme}`}">
                <div id="root">${markup}</div>
            </body>
        </html>`;
};
