"use client";

import { useCallback, useMemo } from "react";
import {
  App,
  blocksPlugin,
  outlinePlugin,
} from "@reacteditor/core";
import createTailwindCdnPlugin from "@reacteditor/plugin-tailwind-cdn";
import { aiPlugin } from "@reacteditor/plugin-ai";
import "@reacteditor/core/dist/index.css";
import "@reacteditor/plugin-ai/styles.css";
import { createConfig } from "@/editor/config";
import { ShopifyProvider } from "@/editor/contexts/shopify-context";

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

const SHOPIFY_DOMAIN =
  process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN ?? "mock.shop";
const STOREFRONT_TOKEN =
  process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN ?? "";

export default function AppClient({
  pages,
  currentPath,
}: {
  pages: Pages;
  currentPath: string;
}) {
  const config = useMemo(
    () =>
      createConfig({
        domain: SHOPIFY_DOMAIN,
        token: STOREFRONT_TOKEN || null,
      }),
    [],
  );

  const plugins = useMemo(
    () => [
      createTailwindCdnPlugin(),
      aiPlugin({
        api: "/api/chat",
        attachments: true,
        body: { route: currentPath },
      }),
      blocksPlugin(),
      outlinePlugin(),
    ],
    [currentPath],
  );

  const handlePublish = useCallback(
    (data: any, route?: string) => {
      const path = route ?? currentPath;
      if (typeof window !== "undefined" && window.parent !== window) {
        window.parent.postMessage(
          { type: "PUBLISH", path, data },
          "*",
        );
      }
    },
    [currentPath],
  );

  return (
    <ShopifyProvider domain={SHOPIFY_DOMAIN} token={STOREFRONT_TOKEN}>
      <App
        config={config as any}
        pages={pages as any}
        currentPath={currentPath}
        plugins={plugins}
        iframe={{ enabled: true }}
        onPublish={handlePublish}
      />
    </ShopifyProvider>
  );
}
