"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { v4 as uuidv4 } from "uuid";
import { Button } from "../../ui/button";
import { ButtonGroup } from "../../ui/button-group";
import { Input } from "../../ui/input";
import { Label } from "../../ui/label";
import { Separator } from "../../ui/separator";
import { Badge } from "../../ui/badge";
import { ArrowLeft, Save, ExternalLink } from "lucide-react";
import Link from "next/link";
import { toast } from "sonner";
import { BlockPicker } from "./block-picker";
import { BlockCanvas } from "./block-canvas";
import { BlockPreviewCanvas } from "./block-preview-canvas";
import { BlockSettingsPanel } from "./block-settings-panel";
import { PageSettingsPanel } from "./page-settings-panel";
import { EntityFieldsSidebar } from "./entity-fields-sidebar";
import { StatusSelector } from "./status-selector";
import { BlockService } from "../../../lib/services/block.service";
import { useSidebar } from "../../../contexts/sidebar-context";
import { cn } from "../../../lib/utils";
function getTeamId() {
  if (typeof window !== "undefined") {
    return localStorage.getItem("activeTeamId");
  }
  return null;
}
function buildApiHeaders(includeContentType = false) {
  const headers = {};
  if (includeContentType) {
    headers["Content-Type"] = "application/json";
  }
  const teamId = getTeamId();
  if (teamId) {
    headers["x-team-id"] = teamId;
  }
  headers["x-builder-source"] = "true";
  return headers;
}
function BuilderEditorView({ entitySlug, entityConfig, id, mode }) {
  var _a, _b;
  const router = useRouter();
  const t = useTranslations("admin.builder");
  const queryClient = useQueryClient();
  const { isCollapsed } = useSidebar();
  const [blocks, setBlocks] = useState([]);
  const [selectedBlockId, setSelectedBlockId] = useState(null);
  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState("");
  const [status, setStatus] = useState("draft");
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [viewMode, setViewMode] = useState("preview");
  const [leftSidebarMode, setLeftSidebarMode] = useState("blocks");
  const [pageSettings, setPageSettings] = useState({
    seo: {},
    customFields: []
  });
  const [entityFields, setEntityFields] = useState({});
  const showFieldsOption = useMemo(() => {
    var _a2, _b2, _c;
    return (((_b2 = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFields) == null ? void 0 : _b2.length) ?? 0) > 0 || ((_c = entityConfig.taxonomies) == null ? void 0 : _c.enabled);
  }, [entityConfig]);
  const availableBlocks = useMemo(() => {
    const allBlocks = BlockService.getAll();
    return allBlocks.filter(
      (block) => {
        var _a2, _b2;
        return ((_a2 = block.scope) == null ? void 0 : _a2.includes(entitySlug)) || ((_b2 = block.scope) == null ? void 0 : _b2.includes("*"));
      }
    );
  }, [entitySlug]);
  const { data: entityData, isLoading } = useQuery({
    queryKey: [entitySlug, id],
    queryFn: async () => {
      const response = await fetch(`/api/v1/${entitySlug}/${id}`, {
        headers: buildApiHeaders()
      });
      if (!response.ok) throw new Error(`Failed to fetch ${entitySlug}`);
      const data = await response.json();
      return data;
    },
    enabled: mode === "edit" && !!id
  });
  useEffect(() => {
    var _a2, _b2;
    if (mode === "edit" && (entityData == null ? void 0 : entityData.data)) {
      const entity = entityData.data;
      setTitle(entity.title ?? "");
      setSlug(entity.slug ?? "");
      setStatus(entity.status || "draft");
      setBlocks(entity.blocks || []);
      setPageSettings(entity.settings || { seo: {}, customFields: [] });
      const fields = {};
      (_b2 = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFields) == null ? void 0 : _b2.forEach((field) => {
        if (entity[field] !== void 0) {
          fields[field] = entity[field];
        }
      });
      setEntityFields(fields);
    }
  }, [entityData, entityConfig, mode]);
  useEffect(() => {
    var _a2, _b2;
    if (mode === "create") {
      setHasUnsavedChanges(title.length > 0 || blocks.length > 0 || status !== "draft");
      return;
    }
    if (!(entityData == null ? void 0 : entityData.data)) return;
    const entity = entityData.data;
    const hasChanges = title !== entity.title || slug !== entity.slug || status !== (entity.status || "draft") || JSON.stringify(blocks) !== JSON.stringify(entity.blocks || []) || JSON.stringify(pageSettings) !== JSON.stringify(entity.settings || { seo: {}, customFields: [] }) || JSON.stringify(entityFields) !== JSON.stringify(
      ((_b2 = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFields) == null ? void 0 : _b2.reduce((acc, field) => {
        if (entity[field] !== void 0) acc[field] = entity[field];
        return acc;
      }, {})) || {}
    );
    setHasUnsavedChanges(hasChanges);
  }, [title, slug, status, blocks, pageSettings, entityFields, entityData, entityConfig, mode]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const url = mode === "create" ? `/api/v1/${entitySlug}` : `/api/v1/${entitySlug}/${id}`;
      const response = await fetch(url, {
        method: mode === "create" ? "POST" : "PATCH",
        headers: buildApiHeaders(true),
        body: JSON.stringify(data)
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || `Failed to save ${entitySlug}`);
      }
      return response.json();
    },
    onSuccess: (response) => {
      var _a2;
      if (mode === "create") {
        const newId = (_a2 = response.data) == null ? void 0 : _a2.id;
        if (newId) {
          toast.success(t("messages.created"));
          router.push(`/dashboard/${entitySlug}/${newId}/edit`);
        }
      } else {
        queryClient.invalidateQueries({ queryKey: [entitySlug, id] });
        queryClient.invalidateQueries({ queryKey: [entitySlug] });
        toast.success(t("messages.saved"));
        setHasUnsavedChanges(false);
      }
    },
    onError: (error) => {
      toast.error(error.message);
    }
  });
  const handleSave = useCallback(() => {
    const data = {
      title,
      slug,
      blocks,
      status,
      settings: pageSettings,
      ...entityFields
    };
    saveMutation.mutate(data);
  }, [title, slug, blocks, status, pageSettings, entityFields, saveMutation]);
  const handleAddBlock = useCallback((blockSlug) => {
    const newBlock = {
      id: uuidv4(),
      blockSlug,
      props: {}
    };
    setBlocks((prev) => [...prev, newBlock]);
    setSelectedBlockId(newBlock.id);
  }, []);
  const handleRemoveBlock = useCallback((blockId) => {
    setBlocks((prev) => prev.filter((b) => b.id !== blockId));
    if (selectedBlockId === blockId) {
      setSelectedBlockId(null);
    }
  }, [selectedBlockId]);
  const handleDuplicateBlock = useCallback((blockId) => {
    const block = blocks.find((b) => b.id === blockId);
    if (block) {
      const duplicated = {
        ...block,
        id: uuidv4(),
        props: { ...block.props }
      };
      const index = blocks.findIndex((b) => b.id === blockId);
      const newBlocks = [...blocks];
      newBlocks.splice(index + 1, 0, duplicated);
      setBlocks(newBlocks);
      setSelectedBlockId(duplicated.id);
    }
  }, [blocks]);
  const handleUpdateBlockProps = useCallback((blockId, props) => {
    setBlocks((prev) => prev.map(
      (block) => block.id === blockId ? { ...block, props } : block
    ));
  }, []);
  const handleReorderBlocks = useCallback((newBlocks) => {
    setBlocks(newBlocks);
  }, []);
  const handleMoveBlockUp = useCallback((blockId) => {
    setBlocks((prev) => {
      const index = prev.findIndex((b) => b.id === blockId);
      if (index <= 0) return prev;
      const newBlocks = [...prev];
      [newBlocks[index - 1], newBlocks[index]] = [newBlocks[index], newBlocks[index - 1]];
      return newBlocks;
    });
  }, []);
  const handleMoveBlockDown = useCallback((blockId) => {
    setBlocks((prev) => {
      const index = prev.findIndex((b) => b.id === blockId);
      if (index < 0 || index >= prev.length - 1) return prev;
      const newBlocks = [...prev];
      [newBlocks[index], newBlocks[index + 1]] = [newBlocks[index + 1], newBlocks[index]];
      return newBlocks;
    });
  }, []);
  const handleEntityFieldChange = useCallback((field, value) => {
    setEntityFields((prev) => ({ ...prev, [field]: value }));
  }, []);
  const handleLeftSidebarToggle = useCallback((value) => {
    if (!value || value === leftSidebarMode) {
      setLeftSidebarMode("none");
    } else {
      setLeftSidebarMode(value);
    }
  }, [leftSidebarMode]);
  const selectedBlock = selectedBlockId ? blocks.find((b) => b.id === selectedBlockId) : void 0;
  const publicUrl = useMemo(() => {
    var _a2, _b2, _c;
    if (status !== "published" || !slug) return null;
    const basePath = ((_a2 = entityConfig.access) == null ? void 0 : _a2.basePath) ?? ((_c = (_b2 = entityConfig.builder) == null ? void 0 : _b2.public) == null ? void 0 : _c.basePath) ?? "";
    return basePath === "/" ? `/${slug}` : `${basePath}/${slug}`;
  }, [status, slug, entityConfig]);
  const leftSidebarOptions = useMemo(() => {
    const options = [
      {
        value: "blocks",
        label: t("sidebar.blocks"),
        dataCy: "sidebar-blocks"
      }
    ];
    if (showFieldsOption) {
      options.push({
        value: "fields",
        label: t("sidebar.fields"),
        dataCy: "sidebar-fields"
      });
    }
    return options;
  }, [t, showFieldsOption]);
  const statusOptions = useMemo(() => {
    return [
      { value: "draft", label: t("status.draft") },
      { value: "published", label: t("status.published") },
      { value: "scheduled", label: t("status.scheduled") },
      { value: "archived", label: t("status.archived") }
    ];
  }, [t]);
  if (mode === "edit" && isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-screen", children: /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t("loading") }) });
  }
  return /* @__PURE__ */ jsxs("div", { className: cn(
    "fixed inset-0 pt-14 pb-20 lg:top-16 lg:pt-0 lg:pb-0 flex flex-col bg-background z-20 transition-all duration-300",
    isCollapsed ? "lg:left-16" : "lg:left-64"
  ), "data-cy": "builder-editor", children: [
    /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b bg-background p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", asChild: true, children: /* @__PURE__ */ jsxs(Link, { href: `/dashboard/${entitySlug}`, children: [
          /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4 mr-2" }),
          t("back")
        ] }) }),
        /* @__PURE__ */ jsx(Separator, { orientation: "vertical", className: "h-6" }),
        /* @__PURE__ */ jsx("div", { "data-cy": "left-sidebar-toggle", children: /* @__PURE__ */ jsx(
          ButtonGroup,
          {
            options: leftSidebarOptions,
            value: leftSidebarMode === "none" ? void 0 : leftSidebarMode,
            onChange: handleLeftSidebarToggle,
            size: "sm"
          }
        ) }),
        /* @__PURE__ */ jsx(Separator, { orientation: "vertical", className: "h-6" }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "entity-title", className: "text-xs text-muted-foreground", children: t("fields.title") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "entity-title",
                value: title,
                onChange: (e) => setTitle(e.target.value),
                className: "h-8 w-64",
                placeholder: t("placeholders.title"),
                "data-cy": "editor-title-input"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "entity-slug", className: "text-xs text-muted-foreground", children: t("fields.slug") }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "/" }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "entity-slug",
                  value: slug,
                  onChange: (e) => setSlug(e.target.value),
                  className: "h-8 w-48 font-mono text-sm",
                  placeholder: t("placeholders.slug"),
                  "data-cy": "editor-slug-input"
                }
              )
            ] })
          ] }),
          publicUrl && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "sm",
              asChild: true,
              className: "h-6 px-2",
              children: /* @__PURE__ */ jsxs(Link, { href: publicUrl, target: "_blank", children: [
                /* @__PURE__ */ jsx(ExternalLink, { className: "h-3.5 w-3.5 mr-1" }),
                t("actions.viewPage")
              ] })
            }
          ),
          hasUnsavedChanges && /* @__PURE__ */ jsx(Badge, { variant: "secondary", children: t("status.unsaved") })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsx("div", { "data-cy": "view-mode-toggle", children: /* @__PURE__ */ jsx(
          ButtonGroup,
          {
            options: [
              { value: "layout", label: t("viewMode.layout"), dataCy: "mode-layout" },
              { value: "preview", label: t("viewMode.preview"), dataCy: "mode-preview" }
            ],
            value: viewMode,
            onChange: (value) => setViewMode(value),
            size: "sm"
          }
        ) }),
        /* @__PURE__ */ jsx(Separator, { orientation: "vertical", className: "h-6" }),
        /* @__PURE__ */ jsx(
          StatusSelector,
          {
            value: status,
            onChange: setStatus,
            disabled: saveMutation.isPending,
            options: statusOptions
          }
        ),
        /* @__PURE__ */ jsx(
          Badge,
          {
            variant: status === "published" ? "default" : "secondary",
            className: status === "published" ? "bg-success text-success-foreground" : "",
            "data-cy": "status-badge",
            children: ((_a = statusOptions.find((o) => o.value === status)) == null ? void 0 : _a.label) || status
          }
        ),
        /* @__PURE__ */ jsxs(
          Button,
          {
            size: "sm",
            onClick: handleSave,
            disabled: !hasUnsavedChanges || saveMutation.isPending,
            "data-cy": "save-btn",
            children: [
              /* @__PURE__ */ jsx(Save, { className: "h-4 w-4 mr-2" }),
              saveMutation.isPending ? t("actions.saving") : t("actions.save")
            ]
          }
        )
      ] })
    ] }) }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-1 overflow-hidden", children: [
      leftSidebarMode !== "none" && /* @__PURE__ */ jsxs("div", { className: "w-80 border-r overflow-hidden shrink-0", children: [
        leftSidebarMode === "blocks" && /* @__PURE__ */ jsx(BlockPicker, { blocks: availableBlocks, onAddBlock: handleAddBlock }),
        leftSidebarMode === "fields" && showFieldsOption && /* @__PURE__ */ jsx(
          EntityFieldsSidebar,
          {
            entityConfig,
            fields: entityFields,
            onChange: handleEntityFieldChange
          }
        )
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto bg-gray-100", children: viewMode === "layout" ? /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "max-w-4xl mx-auto", children: [
        /* @__PURE__ */ jsx(
          BlockCanvas,
          {
            blocks,
            selectedBlockId,
            onSelectBlock: setSelectedBlockId,
            onRemoveBlock: handleRemoveBlock,
            onDuplicateBlock: handleDuplicateBlock,
            onReorder: handleReorderBlocks,
            onUpdateProps: handleUpdateBlockProps,
            onAddBlock: handleAddBlock
          }
        ),
        ((_b = entityConfig.builder) == null ? void 0 : _b.seo) && /* @__PURE__ */ jsx(
          PageSettingsPanel,
          {
            settings: pageSettings,
            onChange: setPageSettings
          }
        )
      ] }) }) : /* @__PURE__ */ jsx("div", { className: "bg-background", children: /* @__PURE__ */ jsx(
        BlockPreviewCanvas,
        {
          blocks,
          selectedBlockId,
          onSelectBlock: setSelectedBlockId,
          onMoveUp: handleMoveBlockUp,
          onMoveDown: handleMoveBlockDown
        }
      ) }) }),
      /* @__PURE__ */ jsx("div", { className: "w-96 border-l overflow-hidden", children: /* @__PURE__ */ jsx(
        BlockSettingsPanel,
        {
          block: selectedBlock,
          onUpdateProps: (props) => {
            if (selectedBlockId) {
              handleUpdateBlockProps(selectedBlockId, props);
            }
          },
          onRemove: () => {
            if (selectedBlockId) {
              handleRemoveBlock(selectedBlockId);
            }
          }
        }
      ) })
    ] })
  ] });
}
export {
  BuilderEditorView
};
