import { useCallback, useMemo, useRef, useState } from "react";
import { App as ReactEditorApp } from "@reacteditor/core";
import "@reacteditor/core/react-editor.css";
import createTailwindCdnPlugin from "@reacteditor/plugin-tailwind-cdn";
import { mediaPlugin } from "@reacteditor/plugin-media";
import "@reacteditor/plugin-media/styles.css";
import { aiPlugin } from "@reacteditor/plugin-ai";
import "@reacteditor/plugin-ai/styles.css";
import { createConfig } from "@/react-editor.config";
import { ShopifyProvider } from "@/contexts/shopify-context";
import { frontendAiMediaAdapter } from "@/services/media-adapter";
import schemaJson from "../app.schema.json";

const AI_API_KEY = (import.meta.env.VITE_API_KEY as string | undefined) ?? "";

type Pages = Record<string, { root: any; content: any[] }>;

const SHOPIFY_DOMAIN =
  (import.meta.env.VITE_SHOPIFY_DOMAIN as string | undefined) ?? "mock.shop";
const STOREFRONT_TOKEN =
  (import.meta.env.VITE_SHOPIFY_STOREFRONT_ACCESS_TOKEN as
    | string
    | undefined) ?? "";

function readPathname() {
  if (typeof window === "undefined") return "/";
  const p = window.location.pathname;
  return p === "" ? "/" : p;
}

export default function App() {
  const pages = schemaJson as Pages;
  const [currentPath, setCurrentPath] = useState<string>(readPathname);
  const latestDataRef = useRef<any>(null);

  const handleChange = useCallback((data: any) => {
    latestDataRef.current = data;
  }, []);

  const config = useMemo(
    () =>
      createConfig({
        domain: SHOPIFY_DOMAIN,
        token: STOREFRONT_TOKEN || null,
      }),
    [],
  );

  const handlePublish = async (data: any, route?: { key: string }) => {
    console.log({ type: "PUBLISH", data: { data, route: JSON.stringify(route) } });
    if (typeof window !== "undefined" && window.parent !== window) {
      window.parent.postMessage(
        { type: "PUBLISH", data: { data, route } },
        "*",
      );
    }
    await new Promise((resolve) => setTimeout(resolve, 1000));
  };

  const plugins = useMemo(
    () => [createTailwindCdnPlugin()],
    [pages, currentPath, handlePublish],
  );

  return (
    <div className="h-screen w-screen">
      <ShopifyProvider domain={SHOPIFY_DOMAIN} token={STOREFRONT_TOKEN}>
        <ReactEditorApp
          config={config as any}
          pages={pages as any}
          currentPath={currentPath}
          plugins={plugins}
          iframe={{ enabled: true }}
          ui={{
            leftSideBarVisible: false,
          }}
          onPublish={handlePublish}
          onChange={handleChange}
        />
      </ShopifyProvider>
    </div>
  );
}
