"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback } from "react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { Label } from "@open-mercato/ui/primitives/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
import { Badge } from "@open-mercato/ui/primitives/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { EventPatternInput } from "@open-mercato/ui/backend/inputs/EventPatternInput";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Plus, Trash2, Edit2, Zap, X } from "lucide-react";
const FILTER_OPERATORS = [
  { value: "eq", label: "Equals" },
  { value: "neq", label: "Not Equals" },
  { value: "gt", label: "Greater Than" },
  { value: "gte", label: "Greater Than or Equal" },
  { value: "lt", label: "Less Than" },
  { value: "lte", label: "Less Than or Equal" },
  { value: "contains", label: "Contains" },
  { value: "startsWith", label: "Starts With" },
  { value: "endsWith", label: "Ends With" },
  { value: "in", label: "In (array)" },
  { value: "notIn", label: "Not In (array)" },
  { value: "exists", label: "Exists" },
  { value: "notExists", label: "Not Exists" },
  { value: "regex", label: "Regex Match" }
];
const defaultFormValues = {
  triggerId: "",
  name: "",
  description: "",
  eventPattern: "",
  enabled: true,
  priority: 0,
  filterConditions: [],
  contextMappings: [],
  debounceMs: "",
  maxConcurrentInstances: ""
};
function DefinitionTriggersEditor({
  value,
  onChange,
  className
}) {
  const t = useT();
  const [showDialog, setShowDialog] = useState(false);
  const [editingTrigger, setEditingTrigger] = useState(null);
  const [formValues, setFormValues] = useState(defaultFormValues);
  const [deleteConfirmId, setDeleteConfirmId] = useState(null);
  const generateTriggerId = useCallback((name) => {
    return name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/(?:^_+|_+$)/g, "").substring(0, 50) || `trigger_${Date.now()}`;
  }, []);
  const parseConditionValue = (valueStr) => {
    try {
      return JSON.parse(valueStr);
    } catch {
      return valueStr;
    }
  };
  const buildTriggerFromForm = useCallback((values) => {
    const config = {};
    if (values.filterConditions.length > 0) {
      config.filterConditions = values.filterConditions.map((fc) => ({
        field: fc.field,
        operator: fc.operator,
        value: parseConditionValue(fc.value)
      }));
    }
    if (values.contextMappings.length > 0) {
      config.contextMapping = values.contextMappings.map((cm) => ({
        targetKey: cm.targetKey,
        sourceExpression: cm.sourceExpression,
        defaultValue: cm.defaultValue ? parseConditionValue(cm.defaultValue) : void 0
      }));
    }
    if (values.debounceMs) {
      config.debounceMs = parseInt(values.debounceMs, 10);
    }
    if (values.maxConcurrentInstances) {
      config.maxConcurrentInstances = parseInt(values.maxConcurrentInstances, 10);
    }
    return {
      triggerId: values.triggerId || generateTriggerId(values.name),
      name: values.name,
      description: values.description || null,
      eventPattern: values.eventPattern,
      enabled: values.enabled,
      priority: values.priority,
      config: Object.keys(config).length > 0 ? config : null
    };
  }, [generateTriggerId]);
  const handleCreateNew = useCallback(() => {
    setEditingTrigger(null);
    setFormValues(defaultFormValues);
    setShowDialog(true);
  }, []);
  const handleEdit = useCallback((trigger) => {
    setEditingTrigger(trigger);
    setFormValues({
      triggerId: trigger.triggerId,
      name: trigger.name,
      description: trigger.description || "",
      eventPattern: trigger.eventPattern,
      enabled: trigger.enabled,
      priority: trigger.priority,
      filterConditions: trigger.config?.filterConditions?.map((fc) => ({
        field: fc.field,
        operator: fc.operator,
        value: typeof fc.value === "string" ? fc.value : JSON.stringify(fc.value)
      })) || [],
      contextMappings: trigger.config?.contextMapping?.map((cm) => ({
        targetKey: cm.targetKey,
        sourceExpression: cm.sourceExpression,
        defaultValue: cm.defaultValue !== void 0 ? typeof cm.defaultValue === "string" ? cm.defaultValue : JSON.stringify(cm.defaultValue) : ""
      })) || [],
      debounceMs: trigger.config?.debounceMs?.toString() || "",
      maxConcurrentInstances: trigger.config?.maxConcurrentInstances?.toString() || ""
    });
    setShowDialog(true);
  }, []);
  const handleCloseDialog = useCallback(() => {
    setShowDialog(false);
    setEditingTrigger(null);
    setFormValues(defaultFormValues);
  }, []);
  const handleSubmit = useCallback(() => {
    if (!formValues.name.trim()) {
      return;
    }
    if (!formValues.eventPattern.trim()) {
      return;
    }
    const newTrigger = buildTriggerFromForm(formValues);
    if (editingTrigger) {
      onChange(value.map((t2) => t2.triggerId === editingTrigger.triggerId ? newTrigger : t2));
    } else {
      const existingIds = new Set(value.map((t2) => t2.triggerId));
      if (existingIds.has(newTrigger.triggerId)) {
        newTrigger.triggerId = `${newTrigger.triggerId}_${Date.now()}`;
      }
      onChange([...value, newTrigger]);
    }
    handleCloseDialog();
  }, [formValues, editingTrigger, buildTriggerFromForm, value, onChange, handleCloseDialog]);
  const handleDelete = useCallback((triggerId) => {
    onChange(value.filter((t2) => t2.triggerId !== triggerId));
    setDeleteConfirmId(null);
  }, [value, onChange]);
  const addFilterCondition = useCallback(() => {
    setFormValues((prev) => ({
      ...prev,
      filterConditions: [...prev.filterConditions, { field: "", operator: "eq", value: "" }]
    }));
  }, []);
  const removeFilterCondition = useCallback((index) => {
    setFormValues((prev) => ({
      ...prev,
      filterConditions: prev.filterConditions.filter((_, i) => i !== index)
    }));
  }, []);
  const updateFilterCondition = useCallback((index, field, fieldValue) => {
    setFormValues((prev) => ({
      ...prev,
      filterConditions: prev.filterConditions.map(
        (fc, i) => i === index ? { ...fc, [field]: fieldValue } : fc
      )
    }));
  }, []);
  const addContextMapping = useCallback(() => {
    setFormValues((prev) => ({
      ...prev,
      contextMappings: [...prev.contextMappings, { targetKey: "", sourceExpression: "", defaultValue: "" }]
    }));
  }, []);
  const removeContextMapping = useCallback((index) => {
    setFormValues((prev) => ({
      ...prev,
      contextMappings: prev.contextMappings.filter((_, i) => i !== index)
    }));
  }, []);
  const updateContextMapping = useCallback((index, field, fieldValue) => {
    setFormValues((prev) => ({
      ...prev,
      contextMappings: prev.contextMappings.map(
        (cm, i) => i === index ? { ...cm, [field]: fieldValue } : cm
      )
    }));
  }, []);
  return /* @__PURE__ */ jsxs("div", { className, children: [
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-3 md:p-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Zap, { className: "w-5 h-5 text-amber-500" }),
          /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold uppercase text-muted-foreground", children: t("workflows.triggers.title", "Event Triggers") })
        ] }),
        /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: handleCreateNew, className: "w-full sm:w-auto", children: [
          /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
          t("workflows.triggers.add", "Add Trigger")
        ] })
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mb-4", children: t("workflows.triggers.description", "Configure events that automatically start this workflow. When a matching event occurs in the system, a new workflow instance will be created with the mapped context.") }),
      value.length === 0 ? /* @__PURE__ */ jsxs(Alert, { variant: "info", children: [
        /* @__PURE__ */ jsx(AlertTitle, { children: t("workflows.triggers.empty.title", "No triggers configured") }),
        /* @__PURE__ */ jsx(AlertDescription, { children: t("workflows.triggers.empty.description", 'Click "Add Trigger" to create an event trigger that automatically starts this workflow.') })
      ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: value.map((trigger) => /* @__PURE__ */ jsxs(
        "div",
        {
          className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between p-3 rounded-lg border bg-background hover:bg-accent/50 transition-colors",
          children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 min-w-0", children: [
              /* @__PURE__ */ jsx(Badge, { variant: trigger.enabled ? "default" : "secondary", className: "shrink-0", children: trigger.enabled ? t("common.active", "Active") : t("common.disabled", "Disabled") }),
              /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                /* @__PURE__ */ jsx("div", { className: "font-medium text-sm truncate", children: trigger.name }),
                /* @__PURE__ */ jsx("code", { className: "text-xs text-muted-foreground truncate block", children: trigger.eventPattern })
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 self-end sm:self-auto", children: [
              /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => handleEdit(trigger), children: /* @__PURE__ */ jsx(Edit2, { className: "w-4 h-4" }) }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  size: "sm",
                  variant: "ghost",
                  className: "text-destructive hover:text-destructive",
                  onClick: () => setDeleteConfirmId(trigger.triggerId),
                  children: /* @__PURE__ */ jsx(Trash2, { className: "w-4 h-4" })
                }
              )
            ] })
          ]
        },
        trigger.triggerId
      )) })
    ] }),
    /* @__PURE__ */ jsx(Dialog, { open: showDialog, onOpenChange: setShowDialog, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-2xl max-h-[90vh] overflow-y-auto", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: editingTrigger ? t("workflows.triggers.dialog.edit.title", "Edit Event Trigger") : t("workflows.triggers.dialog.create.title", "Create Event Trigger") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("workflows.triggers.dialog.description", "Configure when this workflow should be automatically started based on system events.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4 py-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: "trigger-name", children: [
              t("workflows.triggers.fields.name", "Name"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "trigger-name",
                value: formValues.name,
                onChange: (e) => setFormValues((prev) => ({ ...prev, name: e.target.value })),
                placeholder: t("workflows.triggers.placeholders.name", "Order Created Trigger")
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "trigger-priority", children: t("workflows.triggers.fields.priority", "Priority") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "trigger-priority",
                type: "number",
                value: formValues.priority,
                onChange: (e) => setFormValues((prev) => ({ ...prev, priority: parseInt(e.target.value) || 0 })),
                placeholder: "0"
              }
            ),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.triggers.hints.priority", "Higher priority triggers execute first") })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "trigger-description", children: t("workflows.triggers.fields.description", "Description") }),
          /* @__PURE__ */ jsx(
            Textarea,
            {
              id: "trigger-description",
              value: formValues.description,
              onChange: (e) => setFormValues((prev) => ({ ...prev, description: e.target.value })),
              placeholder: t("workflows.triggers.placeholders.description", "Describe when this trigger should fire..."),
              rows: 2
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsxs(Label, { htmlFor: "trigger-pattern", children: [
            t("workflows.triggers.fields.eventPattern", "Event Pattern"),
            " *"
          ] }),
          /* @__PURE__ */ jsx(
            EventPatternInput,
            {
              value: formValues.eventPattern,
              onChange: (eventPattern) => setFormValues((prev) => ({ ...prev, eventPattern })),
              placeholder: t("workflows.triggers.placeholders.eventPattern")
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.triggers.hints.eventPattern", 'Use * as wildcard: "sales.orders.*" matches any order event') })
        ] }),
        /* @__PURE__ */ jsx(
          SwitchField,
          {
            id: "trigger-enabled",
            label: t("workflows.triggers.fields.enabled", "Enabled"),
            flip: true,
            checked: formValues.enabled,
            onCheckedChange: (checked) => setFormValues((prev) => ({ ...prev, enabled: checked }))
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between", children: [
            /* @__PURE__ */ jsx(Label, { children: t("workflows.triggers.fields.filterConditions", "Filter Conditions") }),
            /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", onClick: addFilterCondition, className: "w-full sm:w-auto", children: [
              /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
              t("workflows.triggers.addCondition", "Add Condition")
            ] })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.triggers.hints.filterConditions", "Only trigger when the event payload matches these conditions (all must match)") }),
          formValues.filterConditions.map((fc, index) => /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                value: fc.field,
                onChange: (e) => updateFilterCondition(index, "field", e.target.value),
                placeholder: "status",
                className: "w-full sm:w-1/3"
              }
            ),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: fc.operator,
                onValueChange: (value2) => updateFilterCondition(index, "operator", value2),
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { size: "lg", className: "w-full sm:w-[140px]", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: FILTER_OPERATORS.map((op) => /* @__PURE__ */ jsx(SelectItem, { value: op.value, children: op.label }, op.value)) })
                ]
              }
            ),
            /* @__PURE__ */ jsx(
              Input,
              {
                value: fc.value,
                onChange: (e) => updateFilterCondition(index, "value", e.target.value),
                placeholder: "submitted",
                className: "flex-1 min-w-0"
              }
            ),
            /* @__PURE__ */ jsx(Button, { size: "icon", variant: "ghost", className: "shrink-0", onClick: () => removeFilterCondition(index), children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" }) })
          ] }, index))
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between", children: [
            /* @__PURE__ */ jsx(Label, { children: t("workflows.triggers.fields.contextMapping", "Context Mapping") }),
            /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", onClick: addContextMapping, className: "w-full sm:w-auto", children: [
              /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-1" }),
              t("workflows.triggers.addMapping", "Add Mapping")
            ] })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.triggers.hints.contextMapping", "Map values from the event payload to the workflow's initial context") }),
          formValues.contextMappings.map((cm, index) => /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Input,
              {
                value: cm.targetKey,
                onChange: (e) => updateContextMapping(index, "targetKey", e.target.value),
                placeholder: "orderId",
                className: "w-full sm:w-1/3"
              }
            ),
            /* @__PURE__ */ jsx("span", { className: "hidden sm:inline text-muted-foreground", children: "=" }),
            /* @__PURE__ */ jsx(
              Input,
              {
                value: cm.sourceExpression,
                onChange: (e) => updateContextMapping(index, "sourceExpression", e.target.value),
                placeholder: "id",
                className: "flex-1 min-w-0"
              }
            ),
            /* @__PURE__ */ jsx(
              Input,
              {
                value: cm.defaultValue,
                onChange: (e) => updateContextMapping(index, "defaultValue", e.target.value),
                placeholder: "default",
                className: "w-full sm:w-24"
              }
            ),
            /* @__PURE__ */ jsx(Button, { size: "icon", variant: "ghost", className: "shrink-0", onClick: () => removeContextMapping(index), children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" }) })
          ] }, index))
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "trigger-debounce", children: t("workflows.triggers.fields.debounceMs", "Debounce (ms)") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "trigger-debounce",
                type: "number",
                value: formValues.debounceMs,
                onChange: (e) => setFormValues((prev) => ({ ...prev, debounceMs: e.target.value })),
                placeholder: "0"
              }
            ),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.triggers.hints.debounce", "Delay to prevent rapid re-triggers") })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "trigger-max-concurrent", children: t("workflows.triggers.fields.maxConcurrent", "Max Concurrent Instances") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "trigger-max-concurrent",
                type: "number",
                value: formValues.maxConcurrentInstances,
                onChange: (e) => setFormValues((prev) => ({ ...prev, maxConcurrentInstances: e.target.value })),
                placeholder: t("workflows.triggers.placeholders.unlimited", "Unlimited")
              }
            ),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.triggers.hints.maxConcurrent", "Limit simultaneous workflow instances") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: handleCloseDialog, children: t("common.cancel", "Cancel") }),
        /* @__PURE__ */ jsx(
          Button,
          {
            onClick: handleSubmit,
            disabled: !formValues.name.trim() || !formValues.eventPattern.trim(),
            children: editingTrigger ? t("common.update", "Update") : t("common.create", "Create")
          }
        )
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!deleteConfirmId, onOpenChange: () => setDeleteConfirmId(null), children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("workflows.triggers.delete.title", "Delete Event Trigger?") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("workflows.triggers.delete.description", "This will remove the event trigger. The change will take effect when you save the workflow definition.") })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setDeleteConfirmId(null), children: t("common.cancel", "Cancel") }),
        /* @__PURE__ */ jsx(
          Button,
          {
            variant: "destructive",
            onClick: () => deleteConfirmId && handleDelete(deleteConfirmId),
            children: t("common.delete", "Delete")
          }
        )
      ] })
    ] }) })
  ] });
}
export {
  DefinitionTriggersEditor
};
//# sourceMappingURL=DefinitionTriggersEditor.js.map
