"use client";
import { jsx, jsxs } from "react/jsx-runtime";
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 { Textarea } from "@open-mercato/ui/primitives/textarea";
import { Trash2, Plus, ChevronUp, ChevronDown } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
const TRIGGER_TYPES = [
  { value: "auto", label: "Automatic" },
  { value: "manual", label: "Manual" },
  { value: "signal", label: "Signal" },
  { value: "timer", label: "Timer" }
];
const ACTIVITY_TYPES = [
  { value: "SEND_EMAIL", label: "Send Email" },
  { value: "CALL_API", label: "Call API" },
  { value: "UPDATE_ENTITY", label: "Update Entity" },
  { value: "EMIT_EVENT", label: "Emit Event" },
  { value: "CALL_WEBHOOK", label: "Call Webhook" },
  { value: "EXECUTE_FUNCTION", label: "Execute Function" },
  { value: "WAIT", label: "Wait" }
];
function TransitionsEditor({ value = [], onChange, steps = [], error }) {
  const t = useT();
  const addTransition = () => {
    const newTransition = {
      transitionId: `transition_${Date.now()}`,
      transitionName: t("workflows.common.newTransition"),
      fromStepId: "",
      toStepId: "",
      trigger: "auto",
      preConditions: [],
      postConditions: [],
      activities: [],
      priority: 100
    };
    onChange([...value, newTransition]);
  };
  const updateTransition = (index, field, fieldValue) => {
    const updated = [...value];
    updated[index] = { ...updated[index], [field]: fieldValue };
    onChange(updated);
  };
  const removeTransition = (index) => {
    onChange(value.filter((_, i) => i !== index));
  };
  const moveTransition = (index, direction) => {
    const newIndex = direction === "up" ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= value.length) return;
    const updated = [...value];
    const temp = updated[index];
    updated[index] = updated[newIndex];
    updated[newIndex] = temp;
    onChange(updated);
  };
  const addActivity = (transitionIndex) => {
    const newActivity = {
      activityId: `activity_${Date.now()}`,
      activityName: t("workflows.common.newActivity"),
      activityType: "CALL_API",
      config: {},
      async: false,
      retryPolicy: {
        maxAttempts: 3,
        retryDelay: 1e3,
        backoffMultiplier: 2
      }
    };
    const updated = [...value];
    updated[transitionIndex] = {
      ...updated[transitionIndex],
      activities: [...updated[transitionIndex].activities || [], newActivity]
    };
    onChange(updated);
  };
  const updateActivity = (transitionIndex, activityIndex, field, fieldValue) => {
    const updated = [...value];
    const activities = [...updated[transitionIndex].activities || []];
    activities[activityIndex] = { ...activities[activityIndex], [field]: fieldValue };
    updated[transitionIndex] = { ...updated[transitionIndex], activities };
    onChange(updated);
  };
  const updateRetryPolicy = (transitionIndex, activityIndex, field, fieldValue) => {
    const updated = [...value];
    const activities = [...updated[transitionIndex].activities || []];
    activities[activityIndex] = {
      ...activities[activityIndex],
      retryPolicy: {
        ...activities[activityIndex].retryPolicy,
        [field]: fieldValue
      }
    };
    updated[transitionIndex] = { ...updated[transitionIndex], activities };
    onChange(updated);
  };
  const removeActivity = (transitionIndex, activityIndex) => {
    const updated = [...value];
    updated[transitionIndex] = {
      ...updated[transitionIndex],
      activities: (updated[transitionIndex].activities || []).filter((_, i) => i !== activityIndex)
    };
    onChange(updated);
  };
  const moveActivity = (transitionIndex, activityIndex, direction) => {
    const activities = value[transitionIndex].activities || [];
    const newIndex = direction === "up" ? activityIndex - 1 : activityIndex + 1;
    if (newIndex < 0 || newIndex >= activities.length) return;
    const updated = [...value];
    const updatedActivities = [...activities];
    const temp = updatedActivities[activityIndex];
    updatedActivities[activityIndex] = updatedActivities[newIndex];
    updatedActivities[newIndex] = temp;
    updated[transitionIndex] = { ...updated[transitionIndex], activities: updatedActivities };
    onChange(updated);
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("workflows.form.descriptions.transitions") }),
        error && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 mt-1", children: error })
      ] }),
      /* @__PURE__ */ jsxs(Button, { type: "button", onClick: addTransition, variant: "outline", size: "sm", className: "w-full sm:w-auto", children: [
        /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-1" }),
        t("workflows.form.addTransition")
      ] })
    ] }),
    value.length === 0 && /* @__PURE__ */ jsx("div", { className: "p-6 text-center text-muted-foreground border rounded-md bg-muted", children: t("workflows.form.noTransitions") }),
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: value.map((transition, index) => /* @__PURE__ */ jsx("div", { className: "p-4 border rounded-md bg-card shadow-sm border-l-4 border-l-blue-500", children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex-1 grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: `transition-${index}-id`, className: "text-xs", children: [
              t("workflows.transitions.transitionId"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: `transition-${index}-id`,
                value: transition.transitionId,
                onChange: (e) => updateTransition(index, "transitionId", e.target.value),
                placeholder: "transition_name",
                className: "mt-1"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: `transition-${index}-name`, className: "text-xs", children: [
              t("workflows.transitions.transitionName"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: `transition-${index}-name`,
                value: transition.transitionName,
                onChange: (e) => updateTransition(index, "transitionName", e.target.value),
                placeholder: t("workflows.transitions.transitionName"),
                className: "mt-1"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 self-end sm:self-auto", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => moveTransition(index, "up"),
              disabled: index === 0,
              title: t("common.moveUp"),
              children: /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => moveTransition(index, "down"),
              disabled: index === value.length - 1,
              title: t("common.moveDown"),
              children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => removeTransition(index),
              title: t("common.delete"),
              children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-red-600" })
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs(Label, { htmlFor: `transition-${index}-from`, className: "text-xs", children: [
            t("workflows.transitions.fromStep"),
            " *"
          ] }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: transition.fromStepId || void 0,
              onValueChange: (value2) => updateTransition(index, "fromStepId", value2 ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { id: `transition-${index}-from`, className: "mt-1", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("workflows.form.selectStep") }) }),
                /* @__PURE__ */ jsx(SelectContent, { children: steps.map((step) => /* @__PURE__ */ jsx(SelectItem, { value: step.stepId, children: step.stepName || step.stepId }, step.stepId)) })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs(Label, { htmlFor: `transition-${index}-to`, className: "text-xs", children: [
            t("workflows.transitions.toStep"),
            " *"
          ] }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: transition.toStepId || void 0,
              onValueChange: (value2) => updateTransition(index, "toStepId", value2 ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { id: `transition-${index}-to`, className: "mt-1", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("workflows.form.selectStep") }) }),
                /* @__PURE__ */ jsx(SelectContent, { children: steps.map((step) => /* @__PURE__ */ jsx(SelectItem, { value: step.stepId, children: step.stepName || step.stepId }, step.stepId)) })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs(Label, { htmlFor: `transition-${index}-trigger`, className: "text-xs", children: [
            t("workflows.transitions.trigger"),
            " *"
          ] }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: transition.trigger,
              onValueChange: (value2) => updateTransition(index, "trigger", value2),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { id: `transition-${index}-trigger`, className: "mt-1", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                /* @__PURE__ */ jsx(SelectContent, { children: TRIGGER_TYPES.map((type) => /* @__PURE__ */ jsx(SelectItem, { value: type.value, children: t(`workflows.transitions.triggers.${type.value}`) }, type.value)) })
              ]
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: `transition-${index}-priority`, className: "text-xs", children: t("workflows.transitions.priority") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `transition-${index}-priority`,
              type: "number",
              value: transition.priority || 100,
              onChange: (e) => updateTransition(index, "priority", parseInt(e.target.value)),
              className: "mt-1"
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: `transition-${index}-preconditions`, className: "text-xs", children: t("workflows.transitions.preConditions") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `transition-${index}-preconditions`,
              value: (transition.preConditions || []).join(", "),
              onChange: (e) => updateTransition(index, "preConditions", e.target.value.split(",").map((s) => s.trim()).filter(Boolean)),
              placeholder: "rule_id_1, rule_id_2",
              className: "mt-1"
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-4 pl-4 border-l-2 border-border", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between mb-3", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs font-semibold text-foreground", children: t("workflows.transitions.activities") }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              onClick: () => addActivity(index),
              variant: "outline",
              size: "sm",
              className: "w-full sm:w-auto",
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "h-3 w-3 mr-1" }),
                t("workflows.form.addActivity")
              ]
            }
          )
        ] }),
        (transition.activities || []).length === 0 && /* @__PURE__ */ jsx("div", { className: "p-3 text-center text-xs text-muted-foreground border rounded-md bg-muted", children: t("workflows.form.noActivitiesInTransition") }),
        /* @__PURE__ */ jsx("div", { className: "space-y-2", children: (transition.activities || []).map((activity, activityIndex) => /* @__PURE__ */ jsx("div", { className: "p-3 border rounded-md bg-muted shadow-sm border-l-4 border-l-green-500", children: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex-1 grid grid-cols-1 sm:grid-cols-2 gap-2", children: [
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-${activityIndex}-id`, className: "text-xs", children: [
                  t("workflows.activities.activityId"),
                  " *"
                ] }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    id: `activity-${index}-${activityIndex}-id`,
                    value: activity.activityId,
                    onChange: (e) => updateActivity(index, activityIndex, "activityId", e.target.value),
                    placeholder: "activity_name",
                    className: "mt-1 text-xs h-8"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-${activityIndex}-name`, className: "text-xs", children: [
                  t("workflows.activities.activityName"),
                  " *"
                ] }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    id: `activity-${index}-${activityIndex}-name`,
                    value: activity.activityName,
                    onChange: (e) => updateActivity(index, activityIndex, "activityName", e.target.value),
                    placeholder: t("workflows.activities.activityName"),
                    className: "mt-1 text-xs h-8"
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 self-end sm:self-auto", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  onClick: () => moveActivity(index, activityIndex, "up"),
                  disabled: activityIndex === 0,
                  title: t("common.moveUp"),
                  children: /* @__PURE__ */ jsx(ChevronUp, { className: "h-3 w-3" })
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  onClick: () => moveActivity(index, activityIndex, "down"),
                  disabled: activityIndex === (transition.activities || []).length - 1,
                  title: t("common.moveDown"),
                  children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3" })
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  onClick: () => removeActivity(index, activityIndex),
                  title: t("common.delete"),
                  children: /* @__PURE__ */ jsx(Trash2, { className: "h-3 w-3 text-red-600" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-2", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-${activityIndex}-type`, className: "text-xs", children: [
                t("workflows.activities.activityType"),
                " *"
              ] }),
              /* @__PURE__ */ jsxs(
                Select,
                {
                  value: activity.activityType,
                  onValueChange: (value2) => updateActivity(index, activityIndex, "activityType", value2),
                  children: [
                    /* @__PURE__ */ jsx(SelectTrigger, { id: `activity-${index}-${activityIndex}-type`, size: "sm", className: "mt-1", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                    /* @__PURE__ */ jsx(SelectContent, { children: ACTIVITY_TYPES.map((type) => /* @__PURE__ */ jsx(SelectItem, { value: type.value, children: t(`workflows.activities.types.${type.value}`) }, type.value)) })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-${activityIndex}-timeout`, className: "text-xs", children: [
                t("workflows.activities.timeout"),
                " (ms)"
              ] }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `activity-${index}-${activityIndex}-timeout`,
                  type: "number",
                  value: activity.timeout || "",
                  onChange: (e) => updateActivity(index, activityIndex, "timeout", e.target.value ? parseInt(e.target.value) : void 0),
                  placeholder: "30000",
                  className: "mt-1 text-xs h-8"
                }
              )
            ] }),
            /* @__PURE__ */ jsx("div", { className: "flex items-end pb-1", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  type: "checkbox",
                  id: `activity-${index}-${activityIndex}-async`,
                  checked: activity.async || false,
                  onChange: (e) => updateActivity(index, activityIndex, "async", e.target.checked),
                  className: "h-3 w-3"
                }
              ),
              /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-${activityIndex}-async`, className: "text-xs cursor-pointer", children: t("workflows.activities.async") })
            ] }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-2", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-${activityIndex}-retry-attempts`, className: "text-xs", children: t("workflows.form.maxRetryAttempts") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `activity-${index}-${activityIndex}-retry-attempts`,
                  type: "number",
                  value: activity.retryPolicy?.maxAttempts || 3,
                  onChange: (e) => updateRetryPolicy(index, activityIndex, "maxAttempts", parseInt(e.target.value)),
                  className: "mt-1 text-xs h-8"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-${activityIndex}-retry-delay`, className: "text-xs", children: [
                t("workflows.form.retryDelay"),
                " (ms)"
              ] }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `activity-${index}-${activityIndex}-retry-delay`,
                  type: "number",
                  value: activity.retryPolicy?.retryDelay || 1e3,
                  onChange: (e) => updateRetryPolicy(index, activityIndex, "retryDelay", parseInt(e.target.value)),
                  className: "mt-1 text-xs h-8"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-${activityIndex}-backoff`, className: "text-xs", children: t("workflows.form.backoffMultiplier") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: `activity-${index}-${activityIndex}-backoff`,
                  type: "number",
                  step: "0.1",
                  value: activity.retryPolicy?.backoffMultiplier || 2,
                  onChange: (e) => updateRetryPolicy(index, activityIndex, "backoffMultiplier", parseFloat(e.target.value)),
                  className: "mt-1 text-xs h-8"
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-${activityIndex}-config`, className: "text-xs", children: [
              t("workflows.activities.config"),
              " (JSON)"
            ] }),
            /* @__PURE__ */ jsx(
              Textarea,
              {
                id: `activity-${index}-${activityIndex}-config`,
                value: JSON.stringify(activity.config || {}, null, 2),
                onChange: (e) => {
                  try {
                    const parsed = JSON.parse(e.target.value);
                    updateActivity(index, activityIndex, "config", parsed);
                  } catch {
                  }
                },
                placeholder: '{"key": "value"}',
                rows: 2,
                className: "mt-1 font-mono text-xs"
              }
            )
          ] })
        ] }) }, activityIndex)) })
      ] })
    ] }) }, index)) })
  ] });
}
export {
  TransitionsEditor
};
//# sourceMappingURL=TransitionsEditor.js.map
