"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 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 ActivitiesEditor({ value = [], onChange, error }) {
  const t = useT();
  const addActivity = () => {
    const newActivity = {
      activityId: `activity_${Date.now()}`,
      activityName: t("workflows.common.newActivity"),
      activityType: "CALL_API",
      config: {},
      async: false,
      retryPolicy: {
        maxAttempts: 3,
        retryDelay: 1e3,
        backoffMultiplier: 2
      }
    };
    onChange([...value, newActivity]);
  };
  const updateActivity = (index, field, fieldValue) => {
    const updated = [...value];
    updated[index] = { ...updated[index], [field]: fieldValue };
    onChange(updated);
  };
  const updateRetryPolicy = (index, field, fieldValue) => {
    const updated = [...value];
    updated[index] = {
      ...updated[index],
      retryPolicy: {
        ...updated[index].retryPolicy,
        [field]: fieldValue
      }
    };
    onChange(updated);
  };
  const removeActivity = (index) => {
    onChange(value.filter((_, i) => i !== index));
  };
  const moveActivity = (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);
  };
  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.activities") }),
        error && /* @__PURE__ */ jsx("p", { className: "text-sm text-red-600 mt-1", children: error })
      ] }),
      /* @__PURE__ */ jsxs(Button, { type: "button", onClick: addActivity, variant: "outline", size: "sm", className: "w-full sm:w-auto", children: [
        /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-1" }),
        t("workflows.form.addActivity")
      ] })
    ] }),
    value.length === 0 && /* @__PURE__ */ jsx("div", { className: "p-6 text-center text-muted-foreground border rounded-md bg-muted", children: t("workflows.form.noActivities") }),
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: value.map((activity, index) => /* @__PURE__ */ jsx("div", { className: "p-4 border rounded-md bg-card shadow-sm border-l-4 border-l-green-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: `activity-${index}-id`, className: "text-xs", children: [
              t("workflows.activities.activityId"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: `activity-${index}-id`,
                value: activity.activityId,
                onChange: (e) => updateActivity(index, "activityId", e.target.value),
                placeholder: "activity_name",
                className: "mt-1"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-name`, className: "text-xs", children: [
              t("workflows.activities.activityName"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: `activity-${index}-name`,
                value: activity.activityName,
                onChange: (e) => updateActivity(index, "activityName", e.target.value),
                placeholder: t("workflows.activities.activityName"),
                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: () => moveActivity(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: () => moveActivity(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: () => removeActivity(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: `activity-${index}-type`, className: "text-xs", children: [
            t("workflows.activities.activityType"),
            " *"
          ] }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: activity.activityType,
              onValueChange: (value2) => updateActivity(index, "activityType", value2),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { id: `activity-${index}-type`, 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}-timeout`, className: "text-xs", children: [
            t("workflows.activities.timeout"),
            " (ms)"
          ] }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `activity-${index}-timeout`,
              type: "number",
              value: activity.timeout || "",
              onChange: (e) => updateActivity(index, "timeout", e.target.value ? parseInt(e.target.value) : void 0),
              placeholder: "30000",
              className: "mt-1"
            }
          )
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex items-end pb-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              id: `activity-${index}-async`,
              checked: activity.async || false,
              onChange: (e) => updateActivity(index, "async", e.target.checked),
              className: "h-4 w-4"
            }
          ),
          /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-async`, className: "text-xs cursor-pointer", children: t("workflows.activities.async") })
        ] }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-retry-attempts`, className: "text-xs", children: t("workflows.form.maxRetryAttempts") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `activity-${index}-retry-attempts`,
              type: "number",
              value: activity.retryPolicy?.maxAttempts || 3,
              onChange: (e) => updateRetryPolicy(index, "maxAttempts", parseInt(e.target.value)),
              className: "mt-1"
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-retry-delay`, className: "text-xs", children: [
            t("workflows.form.retryDelay"),
            " (ms)"
          ] }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `activity-${index}-retry-delay`,
              type: "number",
              value: activity.retryPolicy?.retryDelay || 1e3,
              onChange: (e) => updateRetryPolicy(index, "retryDelay", parseInt(e.target.value)),
              className: "mt-1"
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-backoff`, className: "text-xs", children: t("workflows.form.backoffMultiplier") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `activity-${index}-backoff`,
              type: "number",
              step: "0.1",
              value: activity.retryPolicy?.backoffMultiplier || 2,
              onChange: (e) => updateRetryPolicy(index, "backoffMultiplier", parseFloat(e.target.value)),
              className: "mt-1"
            }
          )
        ] })
      ] }),
      activity.activityType === "WAIT" && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-duration`, className: "text-xs", children: t("workflows.activities.waitDuration") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `activity-${index}-duration`,
              value: activity.config?.duration || "",
              onChange: (e) => updateActivity(index, "config", { ...activity.config, duration: e.target.value, until: void 0 }),
              placeholder: t("workflows.activities.waitDurationPlaceholder"),
              disabled: !!activity.config?.until,
              className: "mt-1"
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("workflows.activities.waitDurationDescription") })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "text-xs text-center text-muted-foreground", children: t("workflows.activities.waitOr") }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: `activity-${index}-until`, className: "text-xs", children: t("workflows.activities.waitUntil") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: `activity-${index}-until`,
              type: "datetime-local",
              value: activity.config?.until ? activity.config.until.slice(0, 16) : "",
              onChange: (e) => updateActivity(index, "config", { ...activity.config, until: e.target.value ? new Date(e.target.value).toISOString() : void 0, duration: void 0 }),
              disabled: !!activity.config?.duration,
              className: "mt-1"
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("workflows.activities.waitUntilDescription") })
        ] })
      ] }),
      activity.activityType !== "WAIT" && /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: `activity-${index}-config`, className: "text-xs", children: [
          t("workflows.activities.config"),
          " (JSON)"
        ] }),
        /* @__PURE__ */ jsx(
          Textarea,
          {
            id: `activity-${index}-config`,
            value: JSON.stringify(activity.config || {}, null, 2),
            onChange: (e) => {
              try {
                const parsed = JSON.parse(e.target.value);
                updateActivity(index, "config", parsed);
              } catch {
              }
            },
            placeholder: '{"key": "value"}',
            rows: 3,
            className: "mt-1 font-mono text-xs"
          }
        )
      ] })
    ] }) }, index)) })
  ] });
}
export {
  ActivitiesEditor
};
//# sourceMappingURL=ActivitiesEditor.js.map
