"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useCallback } from 'react';
import { usePluginOverrides, useBasePath } from '@btst/stack/context';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { Input } from '../../../../../../../ui/src/components/input.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../../../../../../../ui/src/components/select.mjs';
import { Popover, PopoverTrigger, PopoverContent } from '../../../../../../../ui/src/components/popover.mjs';
import { Label } from '../../../../../../../ui/src/components/label.mjs';
import { ArrowLeft, Settings2, Save } from 'lucide-react';
import { toast } from 'sonner';
import UIBuilder from '../../../../../../../ui/src/components/ui-builder/index.mjs';
import { useLayerStore } from '../../../../../../../ui/src/lib/ui-builder/store/layer-store.mjs';
import { useRegisterPageAIContext } from '@btst/stack/plugins/ai-chat/client/context';
import { useSuspenseUIBuilderPage, useCreateUIBuilderPage, useUpdateUIBuilderPage } from '../../hooks/ui-builder-hooks.mjs';
import { uiBuilderLocalization } from '../../localization/index.mjs';
import { defaultComponentRegistry } from '../../registry.mjs';

function buildRegistryDescription(registry) {
  const lines = [];
  for (const [name, entry] of Object.entries(registry)) {
    let propsLine = "";
    try {
      const shape = entry.schema?.shape;
      if (shape) {
        const fields = Object.keys(shape).join(", ");
        propsLine = ` \u2014 props: ${fields}`;
      }
    } catch {
    }
    lines.push(`- ${name}${propsLine}`);
  }
  return lines.join("\n");
}
function buildPageDescription(id, slug, layers, registry) {
  const header = id ? `UI Builder \u2014 editing page (slug: "${slug}")` : "UI Builder \u2014 creating new page";
  const layersJson = JSON.stringify(layers, null, 2);
  const registryDesc = buildRegistryDescription(registry);
  const layerFormat = `Each layer: { id: string, type: string, name: string, props: Record<string,any>, children?: ComponentLayer[] | string }`;
  const full = [
    header,
    "",
    `## Current Layers (${layers.length})`,
    layersJson,
    "",
    `## Available Component Types`,
    registryDesc,
    "",
    `## ComponentLayer format`,
    layerFormat
  ].join("\n");
  if (full.length <= 16e3) return full;
  const overhead = [
    header,
    "",
    `## Current Layers (${layers.length})`,
    "",
    "",
    `## Available Component Types`,
    registryDesc,
    "",
    `## ComponentLayer format`,
    layerFormat
  ].join("\n").length + 30;
  const budget = Math.max(0, 16e3 - overhead);
  const truncatedLayers = layersJson.length > budget ? layersJson.slice(0, budget) + "\n...(truncated)" : layersJson;
  return [
    header,
    "",
    `## Current Layers (${layers.length})`,
    truncatedLayers,
    "",
    `## Available Component Types`,
    registryDesc,
    "",
    `## ComponentLayer format`,
    layerFormat
  ].join("\n");
}
function slugify(str) {
  return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
function PageBuilderPage({ id }) {
  if (id) {
    return /* @__PURE__ */ jsx(EditPageBuilderPage, { id });
  }
  return /* @__PURE__ */ jsx(CreatePageBuilderPage, {});
}
function EditPageBuilderPage({ id }) {
  const { page: existingPage } = useSuspenseUIBuilderPage(id);
  return /* @__PURE__ */ jsx(PageBuilderPageContent, { id, existingPage });
}
function CreatePageBuilderPage() {
  return /* @__PURE__ */ jsx(PageBuilderPageContent, {});
}
function parseLayers(layersJson) {
  if (!layersJson) return [];
  try {
    return JSON.parse(layersJson);
  } catch {
    return [];
  }
}
function parseVariables(variablesJson) {
  if (!variablesJson) return [];
  try {
    return JSON.parse(variablesJson);
  } catch {
    return [];
  }
}
function PageBuilderPageContent({
  id,
  existingPage
}) {
  const {
    navigate,
    Link,
    componentRegistry: customRegistry,
    functionRegistry
  } = usePluginOverrides("ui-builder");
  const basePath = useBasePath();
  const createMutation = useCreateUIBuilderPage();
  const updateMutation = useUpdateUIBuilderPage();
  const loc = uiBuilderLocalization;
  const LinkComponent = Link || "a";
  const componentRegistry = customRegistry || defaultComponentRegistry;
  const existingLayers = parseLayers(existingPage?.parsedData?.layers);
  const existingVariables = parseVariables(existingPage?.parsedData?.variables);
  const [slug, setSlug] = useState(existingPage?.slug || "");
  const [status, setStatus] = useState(
    existingPage?.parsedData?.status || "draft"
  );
  const [layers, setLayers] = useState(existingLayers);
  const [variables, setVariables] = useState(existingVariables);
  const [autoSlug, setAutoSlug] = useState(!id);
  useRegisterPageAIContext({
    routeName: id ? "ui-builder-edit-page" : "ui-builder-new-page",
    pageDescription: buildPageDescription(id, slug, layers, componentRegistry),
    suggestions: [
      "Add a hero section",
      "Add a 3-column feature grid",
      "Make the layout full-width",
      "Add a card with a title, description, and button",
      "Replace the layout with a centered single-column design"
    ],
    clientTools: {
      updatePageLayers: async ({ layers: newLayers }) => {
        const store = useLayerStore.getState();
        store.initialize(
          newLayers,
          store.selectedPageId || newLayers[0]?.id,
          void 0,
          store.variables
        );
        return {
          success: true,
          message: `Applied ${newLayers.length} layer(s) to the page`
        };
      }
    }
  });
  const handleLayersChange = useCallback(
    (newLayers) => {
      setLayers(newLayers);
      if (autoSlug && newLayers.length > 0 && newLayers[0]?.name) {
        setSlug(slugify(newLayers[0].name));
      }
    },
    [autoSlug]
  );
  const handleVariablesChange = useCallback((newVariables) => {
    setVariables(newVariables);
  }, []);
  const handleSave = async () => {
    if (!slug.trim()) {
      toast.error(loc.pageBuilder.validation.slugRequired);
      return;
    }
    if (!/^[a-z0-9-]+$/.test(slug)) {
      toast.error(loc.pageBuilder.validation.slugFormat);
      return;
    }
    if (layers.length === 0) {
      toast.error(loc.pageBuilder.validation.layersRequired);
      return;
    }
    try {
      if (id) {
        await updateMutation.mutateAsync({
          id,
          data: {
            layers,
            variables,
            status
          }
        });
        toast.success(loc.pageBuilder.saved);
      } else {
        const newPage = await createMutation.mutateAsync({
          slug,
          layers,
          variables,
          status
        });
        toast.success(loc.pageBuilder.saved);
        navigate?.(`${basePath}/ui-builder/${newPage.id}/edit`);
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : "Unknown error";
      if (message.includes("slug already exists")) {
        toast.error("A page with this slug already exists");
      } else {
        toast.error(loc.pageBuilder.saveError);
      }
    }
  };
  const isSaving = createMutation.isPending || updateMutation.isPending;
  const pageSettingsFields = (isMobile) => /* @__PURE__ */ jsxs(
    "div",
    {
      className: isMobile ? "flex flex-col gap-4" : "flex items-center gap-4",
      children: [
        /* @__PURE__ */ jsxs("div", { className: isMobile ? "flex flex-col gap-2" : "", children: [
          isMobile && /* @__PURE__ */ jsx(Label, { htmlFor: "page-slug", className: "text-sm font-medium", children: loc.pageBuilder.slugLabel }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "page-slug",
              value: slug,
              onChange: (e) => {
                setSlug(e.target.value);
                setAutoSlug(false);
              },
              placeholder: loc.pageBuilder.slugPlaceholder,
              className: isMobile ? "h-9 font-mono text-sm" : "h-8 w-48 font-mono text-sm",
              disabled: !!id
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: isMobile ? "flex flex-col gap-2" : "", children: [
          isMobile && /* @__PURE__ */ jsx(Label, { htmlFor: "page-status", className: "text-sm font-medium", children: loc.pageBuilder.statusLabel }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: status,
              onValueChange: (v) => setStatus(v),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { className: isMobile ? "h-9 w-full" : "h-8 w-28", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                /* @__PURE__ */ jsxs(SelectContent, { children: [
                  /* @__PURE__ */ jsx(SelectItem, { value: "draft", children: loc.pageBuilder.statusOptions.draft }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "published", children: loc.pageBuilder.statusOptions.published }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "archived", children: loc.pageBuilder.statusOptions.archived })
                ] })
              ]
            }
          )
        ] })
      ]
    }
  );
  const navLeftChildren = /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 md:gap-4", children: [
    /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", asChild: true, className: "shrink-0", children: /* @__PURE__ */ jsx(LinkComponent, { href: `${basePath}/ui-builder`, children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4" }) }) }),
    /* @__PURE__ */ jsx("div", { className: "md:hidden", children: /* @__PURE__ */ jsxs(Popover, { children: [
      /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", className: "gap-2", children: [
        /* @__PURE__ */ jsx(Settings2, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsx("span", { className: "max-w-20 truncate font-mono text-xs", children: slug || loc.pageBuilder.slugPlaceholder })
      ] }) }),
      /* @__PURE__ */ jsx(PopoverContent, { className: "z-[9999] w-72", align: "start", children: /* @__PURE__ */ jsxs("div", { className: "grid gap-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx("h4", { className: "font-medium leading-none", children: "Page Settings" }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Configure page slug and status" })
        ] }),
        pageSettingsFields(true)
      ] }) })
    ] }) }),
    /* @__PURE__ */ jsx("div", { className: "hidden md:flex md:items-center md:gap-4", children: pageSettingsFields(false) })
  ] });
  const navRightChildren = /* @__PURE__ */ jsxs(
    Button,
    {
      onClick: handleSave,
      disabled: isSaving,
      size: "icon",
      className: "md:w-auto md:px-4",
      children: [
        /* @__PURE__ */ jsx(Save, { className: "h-4 w-4 md:mr-2" }),
        /* @__PURE__ */ jsx("span", { className: "hidden md:inline", children: isSaving ? loc.pageBuilder.saving : id ? loc.pageBuilder.save : loc.pageBuilder.save })
      ]
    }
  );
  return /* @__PURE__ */ jsx("div", { className: "flex h-full flex-col", "data-testid": "page-builder-page", children: /* @__PURE__ */ jsx(
    UIBuilder,
    {
      initialLayers: existingLayers.length > 0 ? existingLayers : void 0,
      onChange: handleLayersChange,
      initialVariables: existingVariables.length > 0 ? existingVariables : void 0,
      onVariablesChange: handleVariablesChange,
      componentRegistry,
      functionRegistry,
      persistLayerStore: false,
      allowVariableEditing: true,
      allowPagesCreation: false,
      allowPagesDeletion: false,
      showExport: false,
      navLeftChildren,
      navRightChildren
    }
  ) });
}

export { PageBuilderPage };
