"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
import { Separator } from "@open-mercato/ui/primitives/separator";
import { ChevronDown, Plus, Trash2 } from "lucide-react";
import { BusinessRulesSelector } from "./BusinessRulesSelector.js";
import { JsonBuilder } from "@open-mercato/ui/backend/JsonBuilder";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useDialogKeyHandler } from "@open-mercato/ui/hooks/useDialogKeyHandler";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
function EdgeEditDialog({ edge, isOpen, onClose, onSave, onDelete }) {
  const t = useT();
  const { confirm: confirmDialog, ConfirmDialogElement } = useConfirmDialog();
  const [transitionName, setTransitionName] = useState("");
  const [trigger, setTrigger] = useState("auto");
  const [priority, setPriority] = useState("100");
  const [continueOnActivityFailure, setContinueOnActivityFailure] = useState(false);
  const [preConditions, setPreConditions] = useState([]);
  const [postConditions, setPostConditions] = useState([]);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [advancedConfig, setAdvancedConfig] = useState({});
  const [activities, setActivities] = useState([]);
  const [expandedActivities, setExpandedActivities] = useState(/* @__PURE__ */ new Set());
  const [expandedPreConditions, setExpandedPreConditions] = useState(/* @__PURE__ */ new Set());
  const [expandedPostConditions, setExpandedPostConditions] = useState(/* @__PURE__ */ new Set());
  const [showRuleSelector, setShowRuleSelector] = useState(false);
  const [ruleSelectorMode, setRuleSelectorMode] = useState("pre");
  const [ruleDetailsCache, setRuleDetailsCache] = useState(/* @__PURE__ */ new Map());
  const generateNameFromId = (edgeId) => {
    return edgeId.split("_to_").map((part) => part.split("_").map(
      (word) => word.charAt(0).toUpperCase() + word.slice(1)
    ).join(" ")).join(" \u2192 ");
  };
  useEffect(() => {
    if (edge && isOpen) {
      const edgeData = edge.data;
      let loadedTransitionName = "";
      if (edgeData?.transitionName && edgeData.transitionName !== "") {
        loadedTransitionName = edgeData.transitionName;
      } else if (edgeData?.label && edgeData.label !== "" && edgeData.label !== void 0) {
        loadedTransitionName = edgeData.label;
      } else {
        loadedTransitionName = generateNameFromId(edge.id);
      }
      setTransitionName(loadedTransitionName);
      setTrigger(edgeData?.trigger || "auto");
      setPriority((edgeData?.priority || 100).toString());
      setContinueOnActivityFailure(edgeData?.continueOnActivityFailure !== void 0 ? edgeData.continueOnActivityFailure : false);
      const rawPreConditions = edgeData?.preConditions || [];
      const rawPostConditions = edgeData?.postConditions || [];
      setPreConditions(
        Array.isArray(rawPreConditions) ? rawPreConditions.map(
          (c) => typeof c === "string" ? { ruleId: c, required: true } : c
        ) : []
      );
      setPostConditions(
        Array.isArray(rawPostConditions) ? rawPostConditions.map(
          (c) => typeof c === "string" ? { ruleId: c, required: true } : c
        ) : []
      );
      setActivities(edgeData?.activities || []);
      const advancedFields = {};
      if (edgeData?.activities && edgeData.activities.length > 0) {
        advancedFields.activities = edgeData.activities;
      }
      setAdvancedConfig(advancedFields);
      setExpandedActivities(/* @__PURE__ */ new Set());
      setExpandedPreConditions(/* @__PURE__ */ new Set());
      setExpandedPostConditions(/* @__PURE__ */ new Set());
    }
  }, [edge, isOpen]);
  const toggleActivity = (index) => {
    const newExpanded = new Set(expandedActivities);
    if (newExpanded.has(index)) {
      newExpanded.delete(index);
    } else {
      newExpanded.add(index);
    }
    setExpandedActivities(newExpanded);
  };
  const addActivity = () => {
    const newActivity = {
      activityId: `activity_${Date.now()}`,
      activityName: t("workflows.common.newActivity"),
      activityType: "CALL_API",
      config: {},
      timeout: "",
      retryPolicy: {
        maxAttempts: 3,
        initialIntervalMs: 1e3,
        backoffCoefficient: 2,
        maxIntervalMs: 1e4
      }
    };
    setActivities((prev) => [...prev, newActivity]);
    const newExpanded = new Set(expandedActivities);
    newExpanded.add(activities.length);
    setExpandedActivities(newExpanded);
  };
  const removeActivity = async (index) => {
    const confirmed = await confirmDialog({
      title: t("workflows.edgeEditor.confirmRemoveActivity"),
      variant: "destructive"
    });
    if (confirmed) {
      setActivities((prev) => prev.filter((_, i) => i !== index));
      const newExpanded = new Set(expandedActivities);
      newExpanded.delete(index);
      setExpandedActivities(newExpanded);
    }
  };
  const updateActivity = (index, field, value) => {
    const updated = [...activities];
    updated[index] = { ...updated[index], [field]: value };
    setActivities(updated);
  };
  const updateActivityRetryPolicy = (index, field, value) => {
    const updated = [...activities];
    updated[index] = {
      ...updated[index],
      retryPolicy: {
        ...updated[index].retryPolicy,
        [field]: value
      }
    };
    setActivities(updated);
  };
  const togglePreCondition = (index) => {
    const newExpanded = new Set(expandedPreConditions);
    if (newExpanded.has(index)) {
      newExpanded.delete(index);
    } else {
      newExpanded.add(index);
    }
    setExpandedPreConditions(newExpanded);
  };
  const togglePostCondition = (index) => {
    const newExpanded = new Set(expandedPostConditions);
    if (newExpanded.has(index)) {
      newExpanded.delete(index);
    } else {
      newExpanded.add(index);
    }
    setExpandedPostConditions(newExpanded);
  };
  const openRuleSelector = (mode) => {
    setRuleSelectorMode(mode);
    setShowRuleSelector(true);
  };
  const closeRuleSelector = () => {
    setShowRuleSelector(false);
  };
  const handleRuleSelected = (ruleId, rule) => {
    setRuleDetailsCache((prev) => new Map(prev).set(ruleId, rule));
    if (ruleSelectorMode === "pre") {
      if (!preConditions.find((c) => c.ruleId === ruleId)) {
        setPreConditions((prev) => [...prev, { ruleId, required: true }]);
      }
    } else {
      if (!postConditions.find((c) => c.ruleId === ruleId)) {
        setPostConditions((prev) => [...prev, { ruleId, required: true }]);
      }
    }
    closeRuleSelector();
  };
  const removePreCondition = (index) => {
    setPreConditions((prev) => prev.filter((_, i) => i !== index));
    const newExpanded = new Set(expandedPreConditions);
    newExpanded.delete(index);
    setExpandedPreConditions(newExpanded);
  };
  const removePostCondition = (index) => {
    setPostConditions((prev) => prev.filter((_, i) => i !== index));
    const newExpanded = new Set(expandedPostConditions);
    newExpanded.delete(index);
    setExpandedPostConditions(newExpanded);
  };
  const updatePreCondition = (index, field, value) => {
    const updated = [...preConditions];
    updated[index] = { ...updated[index], [field]: value };
    setPreConditions(updated);
  };
  const updatePostCondition = (index, field, value) => {
    const updated = [...postConditions];
    updated[index] = { ...updated[index], [field]: value };
    setPostConditions(updated);
  };
  const getBusinessRuleDetails = (ruleId) => {
    return ruleDetailsCache.get(ruleId) || null;
  };
  const handleSave = () => {
    if (!edge) return;
    const updates = {
      transitionName,
      label: transitionName,
      // Keep label for backward compatibility
      trigger,
      priority: parseInt(priority) || 100,
      continueOnActivityFailure,
      preConditions: preConditions.length > 0 ? preConditions : void 0,
      postConditions: postConditions.length > 0 ? postConditions : void 0,
      activities: activities.length > 0 ? activities : void 0
    };
    if (advancedConfig && Object.keys(advancedConfig).length > 0) {
      Object.assign(updates, advancedConfig);
    }
    onSave(edge.id, updates);
    onClose();
  };
  const handleDelete = () => {
    if (!edge) return;
    onDelete(edge.id);
  };
  const handleKeyDown = useDialogKeyHandler({ onConfirm: handleSave, onCancel: onClose });
  if (!isOpen || !edge) return null;
  const triggerVariant = trigger === "auto" ? "default" : trigger === "manual" ? "secondary" : "outline";
  return /* @__PURE__ */ jsxs(Dialog, { open: isOpen, onOpenChange: onClose, children: [
    /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-4xl max-h-[90vh] overflow-y-auto", onKeyDown: handleKeyDown, children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
          /* @__PURE__ */ jsx(DialogTitle, { children: t("workflows.edgeEditor.title") }),
          /* @__PURE__ */ jsx(Badge, { variant: triggerVariant, className: "text-xs", children: t(`workflows.transitions.triggers.${trigger}`) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(DialogDescription, { children: t("workflows.edgeEditor.description") }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
            /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
              t("workflows.edgeEditor.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__ */ jsxs("span", { className: "font-medium", children: [
              t("workflows.edgeEditor.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__ */ jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "transitionName", children: t("workflows.edgeEditor.transitionName") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "transitionName",
              type: "text",
              value: transitionName,
              onChange: (e) => setTransitionName(e.target.value),
              placeholder: t("workflows.edgeEditor.transitionNamePlaceholder", { name: generateNameFromId(edge.id) }),
              autoFocus: true
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.edgeEditor.transitionNameHint") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "trigger", children: t("workflows.edgeEditor.triggerType") }),
          /* @__PURE__ */ jsxs(Select, { value: trigger, onValueChange: (value) => setTrigger(value), children: [
            /* @__PURE__ */ jsx(SelectTrigger, { id: "trigger", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
            /* @__PURE__ */ jsxs(SelectContent, { children: [
              /* @__PURE__ */ jsx(SelectItem, { value: "auto", children: t("workflows.transitions.triggers.auto") }),
              /* @__PURE__ */ jsx(SelectItem, { value: "manual", children: t("workflows.transitions.triggers.manual") }),
              /* @__PURE__ */ jsx(SelectItem, { value: "signal", children: t("workflows.transitions.triggers.signal") }),
              /* @__PURE__ */ jsx(SelectItem, { value: "timer", children: t("workflows.transitions.triggers.timer") })
            ] })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(`workflows.edgeEditor.triggerDescriptions.${trigger}`) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "priority", children: t("workflows.edgeEditor.priority") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "priority",
              type: "number",
              value: priority,
              onChange: (e) => setPriority(e.target.value),
              placeholder: "100",
              min: "0",
              max: "9999"
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.edgeEditor.priorityHint") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
            /* @__PURE__ */ jsx(
              Checkbox,
              {
                id: "continueOnActivityFailure",
                checked: continueOnActivityFailure,
                onCheckedChange: (checked) => setContinueOnActivityFailure(checked === true)
              }
            ),
            /* @__PURE__ */ jsx(Label, { htmlFor: "continueOnActivityFailure", className: "font-normal cursor-pointer", children: t("workflows.edgeEditor.continueOnActivityFailure") })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground ml-6", children: t("workflows.edgeEditor.continueOnActivityFailureHint") })
        ] }),
        /* @__PURE__ */ jsx(Separator, {}),
        /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs("h3", { className: "text-sm font-semibold", children: [
                t("workflows.edgeEditor.preConditions"),
                " (",
                preConditions.length,
                ")"
              ] }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.edgeEditor.preConditionsHint") })
            ] }),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => openRuleSelector("pre"),
                children: [
                  /* @__PURE__ */ jsx(Plus, { className: "size-3" }),
                  t("workflows.edgeEditor.addRule")
                ]
              }
            )
          ] }),
          preConditions.length === 0 && /* @__PURE__ */ jsx("div", { className: "p-4 text-center text-sm text-muted-foreground bg-muted rounded-lg border", children: t("workflows.edgeEditor.noPreConditions") }),
          /* @__PURE__ */ jsx("div", { className: "space-y-2", children: preConditions.map((condition, index) => {
            const isExpanded = expandedPreConditions.has(index);
            const rule = getBusinessRuleDetails(condition.ruleId);
            return /* @__PURE__ */ jsxs("div", { className: "border border-border rounded-lg bg-muted", children: [
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  onClick: () => togglePreCondition(index),
                  className: "h-auto w-full justify-between rounded-t-lg px-4 py-3 text-left hover:bg-muted/80",
                  children: [
                    /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
                      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: rule?.ruleName || condition.ruleId }),
                        condition.required && /* @__PURE__ */ jsx(Badge, { variant: "destructive", className: "text-xs", children: t("workflows.edgeEditor.required") }),
                        rule && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: rule.ruleType })
                      ] }),
                      /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: [
                        t("workflows.edgeEditor.ruleId"),
                        ": ",
                        /* @__PURE__ */ jsx("code", { className: "bg-background px-1 rounded", children: condition.ruleId })
                      ] }),
                      rule?.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1 line-clamp-1", children: rule.description })
                    ] }),
                    /* @__PURE__ */ jsx(
                      ChevronDown,
                      {
                        className: `size-5 text-muted-foreground transition-transform ${isExpanded ? "rotate-180" : ""}`
                      }
                    )
                  ]
                }
              ),
              isExpanded && /* @__PURE__ */ jsxs("div", { className: "px-4 pb-4 space-y-3 border-t border-border bg-background", children: [
                /* @__PURE__ */ jsxs("div", { className: "pt-3", children: [
                  /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.ruleId") }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "text",
                      size: "sm",
                      value: condition.ruleId,
                      onChange: (e) => updatePreCondition(index, "ruleId", e.target.value)
                    }
                  )
                ] }),
                /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs font-medium text-foreground", children: [
                  /* @__PURE__ */ jsx(
                    Checkbox,
                    {
                      checked: condition.required,
                      onCheckedChange: (checked) => updatePreCondition(index, "required", checked === true)
                    }
                  ),
                  t("workflows.edgeEditor.requiredCheckbox")
                ] }) }),
                rule && /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-3", children: [
                  /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold text-foreground mb-2", children: t("workflows.edgeEditor.businessRuleDetails") }),
                  /* @__PURE__ */ jsxs("dl", { className: "space-y-1 text-xs", children: [
                    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Name:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.ruleName })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Type:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.ruleType })
                    ] }),
                    rule.ruleCategory && /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Category:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.ruleCategory })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Entity Type:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground font-mono text-xs", children: rule.entityType })
                    ] }),
                    rule.eventType && /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Event Type:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.eventType })
                    ] }),
                    rule.description && /* @__PURE__ */ jsxs("div", { className: "mt-2 pt-2 border-t border-border", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground mb-1", children: "Description:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-muted-foreground", children: rule.description })
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsx("div", { className: "border-t border-border pt-3", children: /* @__PURE__ */ jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "destructive",
                    size: "sm",
                    onClick: () => removePreCondition(index),
                    children: [
                      /* @__PURE__ */ jsx(Trash2, { className: "size-4" }),
                      t("workflows.edgeEditor.removePreCondition")
                    ]
                  }
                ) })
              ] })
            ] }, index);
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs("h3", { className: "text-sm font-semibold", children: [
                t("workflows.edgeEditor.postConditions"),
                " (",
                postConditions.length,
                ")"
              ] }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.edgeEditor.postConditionsHint") })
            ] }),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => openRuleSelector("post"),
                children: [
                  /* @__PURE__ */ jsx(Plus, { className: "size-3" }),
                  t("workflows.edgeEditor.addRule")
                ]
              }
            )
          ] }),
          postConditions.length === 0 && /* @__PURE__ */ jsx("div", { className: "p-4 text-center text-sm text-muted-foreground bg-muted rounded-lg border", children: t("workflows.edgeEditor.noPostConditions") }),
          /* @__PURE__ */ jsx("div", { className: "space-y-2", children: postConditions.map((condition, index) => {
            const isExpanded = expandedPostConditions.has(index);
            const rule = getBusinessRuleDetails(condition.ruleId);
            return /* @__PURE__ */ jsxs("div", { className: "border border-border rounded-lg bg-muted", children: [
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  onClick: () => togglePostCondition(index),
                  className: "h-auto w-full justify-between rounded-t-lg px-4 py-3 text-left hover:bg-muted/80",
                  children: [
                    /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
                      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: rule?.ruleName || condition.ruleId }),
                        condition.required && /* @__PURE__ */ jsx(Badge, { variant: "destructive", className: "text-xs", children: t("workflows.edgeEditor.required") }),
                        rule && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: rule.ruleType })
                      ] }),
                      /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: [
                        t("workflows.edgeEditor.ruleId"),
                        ": ",
                        /* @__PURE__ */ jsx("code", { className: "bg-background px-1 rounded", children: condition.ruleId })
                      ] }),
                      rule?.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1 line-clamp-1", children: rule.description })
                    ] }),
                    /* @__PURE__ */ jsx(
                      ChevronDown,
                      {
                        className: `size-5 text-muted-foreground transition-transform ${isExpanded ? "rotate-180" : ""}`
                      }
                    )
                  ]
                }
              ),
              isExpanded && /* @__PURE__ */ jsxs("div", { className: "px-4 pb-4 space-y-3 border-t border-border bg-background", children: [
                /* @__PURE__ */ jsxs("div", { className: "pt-3", children: [
                  /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.ruleId") }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "text",
                      size: "sm",
                      value: condition.ruleId,
                      onChange: (e) => updatePostCondition(index, "ruleId", e.target.value)
                    }
                  )
                ] }),
                /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs font-medium text-foreground", children: [
                  /* @__PURE__ */ jsx(
                    Checkbox,
                    {
                      checked: condition.required,
                      onCheckedChange: (checked) => updatePostCondition(index, "required", checked === true)
                    }
                  ),
                  t("workflows.edgeEditor.requiredPostCheckbox")
                ] }) }),
                rule && /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-3", children: [
                  /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold text-foreground mb-2", children: t("workflows.edgeEditor.businessRuleDetails") }),
                  /* @__PURE__ */ jsxs("dl", { className: "space-y-1 text-xs", children: [
                    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Name:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.ruleName })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Type:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.ruleType })
                    ] }),
                    rule.ruleCategory && /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Category:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.ruleCategory })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Entity Type:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground font-mono text-xs", children: rule.entityType })
                    ] }),
                    rule.eventType && /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground", children: "Event Type:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: rule.eventType })
                    ] }),
                    rule.description && /* @__PURE__ */ jsxs("div", { className: "mt-2 pt-2 border-t border-border", children: [
                      /* @__PURE__ */ jsx("dt", { className: "font-medium text-foreground mb-1", children: "Description:" }),
                      /* @__PURE__ */ jsx("dd", { className: "text-muted-foreground", children: rule.description })
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsx("div", { className: "border-t border-border pt-3", children: /* @__PURE__ */ jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "destructive",
                    size: "sm",
                    onClick: () => removePostCondition(index),
                    children: [
                      /* @__PURE__ */ jsx(Trash2, { className: "size-4" }),
                      t("workflows.edgeEditor.removePostCondition")
                    ]
                  }
                ) })
              ] })
            ] }, index);
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-4 mt-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
            /* @__PURE__ */ jsxs("h3", { className: "text-sm font-semibold text-foreground", children: [
              t("workflows.edgeEditor.activities"),
              " (",
              activities.length,
              ")"
            ] }),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: addActivity,
                children: [
                  /* @__PURE__ */ jsx(Plus, { className: "size-3" }),
                  t("workflows.edgeEditor.addActivity")
                ]
              }
            )
          ] }),
          activities.length === 0 && /* @__PURE__ */ jsx("div", { className: "p-4 text-center text-sm text-muted-foreground bg-muted rounded-lg border border-border", children: t("workflows.edgeEditor.noActivities") }),
          /* @__PURE__ */ jsx("div", { className: "space-y-2", children: activities.map((activity, index) => {
            const isExpanded = expandedActivities.has(index);
            return /* @__PURE__ */ jsxs("div", { className: "border border-border rounded-lg bg-muted", children: [
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  onClick: () => toggleActivity(index),
                  className: "h-auto w-full justify-between rounded-t-lg px-4 py-3 text-left hover:bg-muted/80",
                  children: [
                    /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
                      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: activity.activityName || activity.label || activity.activityId || `Activity ${index + 1}` }),
                        /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: activity.activityType })
                      ] }),
                      /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: [
                        t("workflows.edgeEditor.activityId"),
                        ": ",
                        /* @__PURE__ */ jsx("code", { className: "bg-background px-1 rounded", children: activity.activityId })
                      ] })
                    ] }),
                    /* @__PURE__ */ jsx(
                      ChevronDown,
                      {
                        className: `size-5 text-muted-foreground transition-transform ${isExpanded ? "rotate-180" : ""}`
                      }
                    )
                  ]
                }
              ),
              isExpanded && /* @__PURE__ */ jsxs("div", { className: "px-4 pb-4 space-y-3 border-t border-border bg-background", children: [
                /* @__PURE__ */ jsxs("div", { className: "pt-3", children: [
                  /* @__PURE__ */ jsxs("label", { className: "block text-xs font-medium text-foreground mb-1", children: [
                    t("workflows.edgeEditor.activityId"),
                    " *"
                  ] }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "text",
                      size: "sm",
                      value: activity.activityId,
                      onChange: (e) => updateActivity(index, "activityId", e.target.value),
                      placeholder: t("workflows.edgeEditor.activityIdPlaceholder")
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsxs("label", { className: "block text-xs font-medium text-foreground mb-1", children: [
                    t("workflows.edgeEditor.activityName"),
                    " *"
                  ] }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "text",
                      size: "sm",
                      value: activity.activityName || "",
                      onChange: (e) => updateActivity(index, "activityName", e.target.value),
                      placeholder: t("workflows.edgeEditor.activityNamePlaceholder")
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsxs("label", { className: "block text-xs font-medium text-foreground mb-1", children: [
                    t("workflows.edgeEditor.activityType"),
                    " *"
                  ] }),
                  /* @__PURE__ */ jsxs(
                    Select,
                    {
                      value: activity.activityType,
                      onValueChange: (value) => updateActivity(index, "activityType", value),
                      children: [
                        /* @__PURE__ */ jsx(SelectTrigger, { size: "sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                        /* @__PURE__ */ jsxs(SelectContent, { children: [
                          /* @__PURE__ */ jsx(SelectItem, { value: "SEND_EMAIL", children: t("workflows.activities.types.SEND_EMAIL") }),
                          /* @__PURE__ */ jsx(SelectItem, { value: "CALL_API", children: t("workflows.activities.types.CALL_API") }),
                          /* @__PURE__ */ jsx(SelectItem, { value: "UPDATE_ENTITY", children: t("workflows.activities.types.UPDATE_ENTITY") }),
                          /* @__PURE__ */ jsx(SelectItem, { value: "EMIT_EVENT", children: t("workflows.activities.types.EMIT_EVENT") }),
                          /* @__PURE__ */ jsx(SelectItem, { value: "CALL_WEBHOOK", children: t("workflows.activities.types.CALL_WEBHOOK") }),
                          /* @__PURE__ */ jsx(SelectItem, { value: "EXECUTE_FUNCTION", children: t("workflows.activities.types.EXECUTE_FUNCTION") }),
                          /* @__PURE__ */ jsx(SelectItem, { value: "WAIT", children: t("workflows.activities.types.WAIT") })
                        ] })
                      ]
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.timeout") }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "text",
                      size: "sm",
                      value: activity.timeout || "",
                      onChange: (e) => updateActivity(index, "timeout", e.target.value),
                      placeholder: t("workflows.edgeEditor.timeoutPlaceholder")
                    }
                  ),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-0.5", children: t("workflows.edgeEditor.timeoutHint") })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-3", children: [
                  /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold text-foreground mb-2", children: t("workflows.edgeEditor.retryPolicy") }),
                  /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-2", children: [
                    /* @__PURE__ */ jsxs("div", { children: [
                      /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.maxAttempts") }),
                      /* @__PURE__ */ jsx(
                        Input,
                        {
                          type: "number",
                          size: "sm",
                          value: activity.retryPolicy?.maxAttempts || "",
                          onChange: (e) => updateActivityRetryPolicy(index, "maxAttempts", parseInt(e.target.value) || 0),
                          placeholder: "3",
                          min: "1",
                          max: "10"
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxs("div", { children: [
                      /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.initialInterval") }),
                      /* @__PURE__ */ jsx(
                        Input,
                        {
                          type: "number",
                          size: "sm",
                          value: activity.retryPolicy?.initialIntervalMs || "",
                          onChange: (e) => updateActivityRetryPolicy(index, "initialIntervalMs", parseInt(e.target.value) || 0),
                          placeholder: "1000",
                          min: "0"
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxs("div", { children: [
                      /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.backoffCoefficient") }),
                      /* @__PURE__ */ jsx(
                        Input,
                        {
                          type: "number",
                          size: "sm",
                          step: "0.1",
                          value: activity.retryPolicy?.backoffCoefficient || "",
                          onChange: (e) => updateActivityRetryPolicy(index, "backoffCoefficient", parseFloat(e.target.value) || 1),
                          placeholder: "2",
                          min: "1",
                          max: "10"
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxs("div", { children: [
                      /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.maxInterval") }),
                      /* @__PURE__ */ jsx(
                        Input,
                        {
                          type: "number",
                          size: "sm",
                          value: activity.retryPolicy?.maxIntervalMs || "",
                          onChange: (e) => updateActivityRetryPolicy(index, "maxIntervalMs", parseInt(e.target.value) || 0),
                          placeholder: "10000",
                          min: "0"
                        }
                      )
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-3", children: [
                  /* @__PURE__ */ jsx("h4", { className: "text-xs font-semibold text-foreground mb-2", children: t("workflows.edgeEditor.activityOptions") }),
                  /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                    /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
                      /* @__PURE__ */ jsx(
                        Checkbox,
                        {
                          id: `activity-async-${index}`,
                          checked: activity.async || false,
                          onCheckedChange: (checked) => updateActivity(index, "async", checked === true)
                        }
                      ),
                      /* @__PURE__ */ jsx("label", { htmlFor: `activity-async-${index}`, className: "text-xs text-foreground cursor-pointer", children: t("workflows.edgeEditor.asyncOption") })
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
                      /* @__PURE__ */ jsx(
                        Checkbox,
                        {
                          id: `activity-compensate-${index}`,
                          checked: activity.compensate || false,
                          onCheckedChange: (checked) => updateActivity(index, "compensate", checked === true)
                        }
                      ),
                      /* @__PURE__ */ jsx("label", { htmlFor: `activity-compensate-${index}`, className: "text-xs text-foreground cursor-pointer", children: t("workflows.edgeEditor.compensateOption") })
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-3", children: [
                  /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-foreground mb-1", children: t("workflows.edgeEditor.configurationJson") }),
                  /* @__PURE__ */ jsx(
                    JsonBuilder,
                    {
                      value: activity.config || {},
                      onChange: (config) => {
                        const updated = [...activities];
                        updated[index] = { ...updated[index], config };
                        setActivities(updated);
                      }
                    }
                  ),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-0.5", children: t("workflows.edgeEditor.configurationHint") })
                ] }),
                /* @__PURE__ */ jsx("div", { className: "border-t border-border pt-3", children: /* @__PURE__ */ jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "destructive",
                    size: "sm",
                    onClick: () => removeActivity(index),
                    children: [
                      /* @__PURE__ */ jsx(Trash2, { className: "size-4" }),
                      t("workflows.edgeEditor.removeActivity")
                    ]
                  }
                ) })
              ] })
            ] }, index);
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "border-t border-border pt-4 mt-4", children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              onClick: () => setShowAdvanced(!showAdvanced),
              className: "h-auto w-full justify-between px-0 py-0 text-left hover:bg-transparent",
              children: [
                /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground", children: t("workflows.edgeEditor.advancedConfiguration") }),
                /* @__PURE__ */ jsx(
                  ChevronDown,
                  {
                    className: `size-5 transition-transform ${showAdvanced ? "rotate-180" : ""}`
                  }
                )
              ]
            }
          ),
          showAdvanced && /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
            /* @__PURE__ */ jsx(
              JsonBuilder,
              {
                value: advancedConfig,
                onChange: setAdvancedConfig
              }
            ),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("workflows.edgeEditor.advancedConfigHint") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { className: "flex justify-between", children: [
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "destructive",
            onClick: handleDelete,
            children: [
              /* @__PURE__ */ jsx(Trash2, { className: "size-4" }),
              t("workflows.edgeEditor.deleteTransition")
            ]
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: onClose,
              children: t("workflows.edgeEditor.cancel")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              onClick: handleSave,
              children: t("workflows.edgeEditor.saveChanges")
            }
          )
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      BusinessRulesSelector,
      {
        isOpen: showRuleSelector,
        onClose: closeRuleSelector,
        onSelect: handleRuleSelected,
        excludeRuleIds: ruleSelectorMode === "pre" ? preConditions.map((c) => c.ruleId) : postConditions.map((c) => c.ruleId),
        title: t("workflows.edgeEditor.selectBusinessRule"),
        description: t("workflows.edgeEditor.selectBusinessRuleDescription", {
          mode: ruleSelectorMode === "pre" ? t("workflows.edgeEditor.preConditions").toLowerCase() : t("workflows.edgeEditor.postConditions").toLowerCase()
        })
      }
    ),
    ConfirmDialogElement
  ] });
}
export {
  EdgeEditDialog
};
//# sourceMappingURL=EdgeEditDialog.js.map
