"use client";

import { useMemo } from "react";
import { useParams } from "next/navigation";
import { Editor } from "@reacteditor/core";
import createTailwindCdnPlugin from "@reacteditor/plugin-tailwind-cdn";
import createShopifyPlugin from "@reacteditor/plugin-shopify";
import { collectionsConfig } from "@/editor.config";
import schema from "@/app.schema.json";

const currentRoute = "/collections/:handle";

export default function CollectionEditorPage() {
  const params = useParams();
  const handle = typeof params?.handle === "string" ? params.handle : "";
  const data = (schema as any)["/collections/:handle"];
  const plugins = useMemo(
    () => [
      createTailwindCdnPlugin(),
      createShopifyPlugin({
        storeDomain:
          process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN ?? "mock.shop",
        publicAccessToken:
          process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN,
      }),
    ],
    [],
  );

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

  return (
    <div className="h-screen w-screen">
      <Editor
        config={collectionsConfig as any}
        data={data}
        currentRoute={currentRoute}
        route={{ key: currentRoute, path: `/collections/${handle}`, params: { handle } }}
        plugins={plugins}
        iframe={{ enabled: true }}
        ui={{ leftSideBarVisible: false }}
        onPublish={handlePublish}
      />
    </div>
  );
}
