"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@open-mercato/ui/primitives/dialog";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Button } from "@open-mercato/ui/primitives/button";
import { Trash2 } from "lucide-react";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { JsonBuilder } from "@open-mercato/ui/backend/JsonBuilder";
import { BusinessRuleConditionsEditor } from "./fields/BusinessRuleConditionsEditor.js";
import { ActivityArrayEditor } from "./fields/ActivityArrayEditor.js";
import { edgeToFormValues, formValuesToEdgeUpdates } from "../lib/edgeFormTransforms.js";
function JsonConfigEditor({ value, setValue, disabled }) {
  return /* @__PURE__ */ jsx(
    JsonBuilder,
    {
      value: value || {},
      onChange: setValue,
      disabled
    }
  );
}
function EdgeEditDialogCrudForm({ edge, isOpen, onClose, onSave, onDelete }) {
  const [initialValues, setInitialValues] = useState({});
  useEffect(() => {
    if (edge && isOpen) {
      const values = edgeToFormValues(edge);
      setInitialValues(values);
    }
  }, [edge, isOpen]);
  const handleSubmit = useCallback(async (values) => {
    if (!edge) return;
    try {
      const updates = formValuesToEdgeUpdates(values, edge);
      onSave(edge.id, updates);
      onClose();
    } catch (error) {
      throw error;
    }
  }, [edge, onSave, onClose]);
  const handleDelete = useCallback(() => {
    if (!edge) return;
    onDelete(edge.id);
  }, [edge, onDelete]);
  const handleKeyDown = useCallback((e) => {
    if (e.key === "Escape") {
      onClose();
    }
  }, [onClose]);
  const groups = useMemo(() => [
    {
      id: "basic",
      title: "Basic Configuration",
      column: 1,
      fields: ["transitionName", "trigger", "priority", "continueOnActivityFailure"]
    },
    {
      id: "businessRules",
      title: "Business Rules",
      column: 1,
      description: "Define pre-conditions (guards) and post-conditions (validations) for this transition",
      fields: ["preConditions", "postConditions"]
    },
    {
      id: "activities",
      title: "Activities",
      column: 1,
      description: "Activities executed when this transition fires",
      fields: ["activities"]
    },
    {
      id: "advanced",
      title: "Advanced Configuration",
      column: 1,
      description: "Additional configuration as JSON (merged with above fields)",
      fields: ["advancedConfig"]
    }
  ], []);
  const fields = useMemo(() => [
    {
      id: "transitionName",
      label: "Transition Name",
      type: "text",
      placeholder: "Enter transition name",
      required: true,
      description: "Display name for this transition"
    },
    {
      id: "trigger",
      label: "Trigger Type",
      type: "select",
      required: true,
      options: [
        { value: "auto", label: "Automatic" },
        { value: "manual", label: "Manual" },
        { value: "signal", label: "Signal" },
        { value: "timer", label: "Timer" }
      ],
      description: "How this transition is triggered"
    },
    {
      id: "priority",
      label: "Priority",
      type: "number",
      placeholder: "100",
      description: "Higher priority transitions are evaluated first (0-9999)"
    },
    {
      id: "continueOnActivityFailure",
      label: "Continue on Activity Failure",
      type: "checkbox",
      description: "If checked, transition completes even if activities fail"
    },
    {
      id: "preConditions",
      label: "Pre-Conditions (Guards)",
      type: "custom",
      description: "Business rules that must pass before transition can fire",
      component: (props) => /* @__PURE__ */ jsx(
        BusinessRuleConditionsEditor,
        {
          ...props,
          value: props.value
        }
      )
    },
    {
      id: "postConditions",
      label: "Post-Conditions (Validations)",
      type: "custom",
      description: "Business rules validated after transition completes",
      component: (props) => /* @__PURE__ */ jsx(
        BusinessRuleConditionsEditor,
        {
          ...props,
          value: props.value
        }
      )
    },
    {
      id: "activities",
      label: "Activities",
      type: "custom",
      description: "Activities executed when this transition fires",
      component: (props) => /* @__PURE__ */ jsx(ActivityArrayEditor, { ...props, value: props.value })
    },
    {
      id: "advancedConfig",
      label: "Advanced Configuration (JSON)",
      type: "custom",
      description: "Additional JSON configuration merged with the transition data",
      component: (props) => /* @__PURE__ */ jsx(JsonConfigEditor, { ...props })
    }
  ], []);
  if (!isOpen || !edge) return null;
  const edgeData = edge.data;
  const trigger = edgeData?.trigger || "auto";
  const triggerVariant = trigger === "auto" ? "default" : trigger === "manual" ? "secondary" : "outline";
  return /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: /* @__PURE__ */ jsxs(
    DialogContent,
    {
      className: "sm:max-w-3xl max-h-[90vh] overflow-hidden flex flex-col !p-0 [&_.grid]:!grid-cols-1",
      onKeyDown: handleKeyDown,
      children: [
        /* @__PURE__ */ jsxs(DialogHeader, { className: "flex-shrink-0 p-6 pb-4 border-b border-border/70", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
            /* @__PURE__ */ jsx(DialogTitle, { children: "Edit Transition" }),
            /* @__PURE__ */ jsx(Badge, { variant: triggerVariant, className: "text-xs", children: trigger === "auto" ? "Automatic" : trigger === "manual" ? "Manual" : trigger === "signal" ? "Signal" : "Timer" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx(DialogDescription, { children: "Configure transition properties, conditions, and activities" }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx("span", { className: "font-medium", children: "ID:" }),
              /* @__PURE__ */ jsx("code", { className: "px-1.5 py-0.5 rounded bg-muted font-mono", children: edge.id })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx("span", { className: "font-medium", children: "Flow:" }),
              /* @__PURE__ */ jsx("code", { className: "px-1.5 py-0.5 rounded bg-muted font-mono", children: edge.source }),
              /* @__PURE__ */ jsx("span", { children: "\u2192" }),
              /* @__PURE__ */ jsx("code", { className: "px-1.5 py-0.5 rounded bg-muted font-mono", children: edge.target })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto min-h-0 px-6 ", children: /* @__PURE__ */ jsx(
          CrudForm,
          {
            fields,
            groups,
            initialValues,
            onSubmit: handleSubmit,
            embedded: true,
            submitLabel: "Save Transition",
            extraActions: /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: handleDelete,
                className: "text-red-600 border-red-200 hover:bg-red-50",
                children: [
                  /* @__PURE__ */ jsx(Trash2, { className: "size-4 mr-2" }),
                  "Delete Transition"
                ]
              }
            )
          }
        ) })
      ]
    }
  ) });
}
export {
  EdgeEditDialogCrudForm
};
//# sourceMappingURL=EdgeEditDialogCrudForm.js.map
