import React from 'react';
import type { ChunkExtractor } from '@loadable/server';
import type { HelmetData } from 'react-helmet';
import type { DehydratedState } from '@tanstack/react-query';

export interface IProps {
  extractor: ChunkExtractor;
  rootHtml: string;
  helmet: HelmetData;
  dehydratedState: DehydratedState;
}

export function Page({ extractor, rootHtml, helmet, dehydratedState }: IProps) {
  const htmlAttrs = helmet.htmlAttributes.toComponent();
  const bodyAttrs = helmet.bodyAttributes.toComponent();

  // You can now collect your script tags
  const scriptElements = extractor.getScriptElements();
  // You can also collect your "preload/prefetch" links
  const linkElements = extractor.getLinkElements();
  // And you can even collect your style tags (if you use "mini-css-extract-plugin")
  const styleElements = extractor.getStyleElements();

  return (
    <html lang="ru" {...htmlAttrs}>
      <head>
        {helmet.title.toComponent()}

        <meta charSet="utf-8" />
        {helmet.meta.toComponent()}

        <link
          rel="preload"
          as="script"
          crossOrigin="anonymous"
          href={`//cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.${process.env.NODE_ENV}.min.js`}
        />
        <link
          rel="preload"
          as="script"
          crossOrigin="anonymous"
          href={`//cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.${process.env.NODE_ENV}.min.js`}
        />

        {helmet.link.toComponent()}
        {linkElements}
        {styleElements}
      </head>
      <body {...bodyAttrs}>
        <div id="root" dangerouslySetInnerHTML={{ __html: rootHtml }} />

        <script
          dangerouslySetInnerHTML={{ __html: `window.__REACT_QUERY_STATE__ = ${JSON.stringify(dehydratedState)};` }}
        />

        <script
          crossOrigin="anonymous"
          src={`//cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.${process.env.NODE_ENV}.min.js`}
        />
        <script
          crossOrigin="anonymous"
          src={`//cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.${process.env.NODE_ENV}.min.js`}
        />

        {scriptElements}
      </body>
    </html>
  );
}
