"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from "react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Label } from "@open-mercato/ui/primitives/label";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { Plus, Trash2, AlertCircle, ChevronUp, ChevronDown } from "lucide-react";
import { BusinessRulesSelector } from "../BusinessRulesSelector.js";
import { apiFetch } from "@open-mercato/ui/backend/utils/api";
import { EmptyState } from "@open-mercato/ui/backend/EmptyState";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
import { ConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function LocalizedMessageTextarea({
  value,
  onChange,
  disabled,
  id,
  placeholder,
  hint
}) {
  const getValidationMessagesString = (messages) => {
    if (!messages) return "";
    return Object.entries(messages).filter(([_, msg]) => msg).map(([locale, msg]) => `${locale}: ${msg}`).join("\n");
  };
  const parseValidationMessagesString = (str) => {
    const result = {};
    str.split("\n").forEach((line) => {
      const match = line.match(/^(\w+):\s*(.*)$/);
      if (match) {
        result[match[1]] = match[2];
      }
    });
    return result;
  };
  const [localValue, setLocalValue] = useState(() => getValidationMessagesString(value));
  useEffect(() => {
    setLocalValue(getValidationMessagesString(value));
  }, [value]);
  const handleBlur = useCallback(() => {
    onChange(parseValidationMessagesString(localValue));
  }, [localValue, onChange]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Textarea,
      {
        id,
        value: localValue,
        onChange: (e) => setLocalValue(e.target.value),
        onBlur: handleBlur,
        placeholder,
        rows: 2,
        className: "mt-1 font-mono text-xs",
        disabled
      }
    ),
    /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: hint })
  ] });
}
function StartPreConditionsEditor({
  value,
  setValue,
  disabled = false
}) {
  const t = useT();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [conditionsWithDetails, setConditionsWithDetails] = useState([]);
  const conditions = Array.isArray(value) ? value : [];
  const updateValue = (newValue) => {
    if (setValue) {
      setValue(newValue);
    }
  };
  useEffect(() => {
    const withDetails = conditions.map((c) => ({
      ...c,
      loading: true
    }));
    setConditionsWithDetails(withDetails);
    conditions.forEach((condition, index) => {
      fetchRuleDetails(condition.ruleId, index);
    });
  }, [JSON.stringify(conditions.map((c) => c.ruleId))]);
  const fetchRuleDetails = async (ruleId, index) => {
    try {
      const params = new URLSearchParams({ ruleId, pageSize: "1" });
      const response = await apiFetch(`/api/business_rules/rules?${params.toString()}`);
      if (response.ok) {
        const data = await response.json();
        const rule = data.items?.[0];
        setConditionsWithDetails((prev) => {
          const updated = [...prev];
          if (updated[index]) {
            updated[index] = {
              ...updated[index],
              ruleName: rule?.ruleName || ruleId,
              ruleType: rule?.ruleType,
              loading: false,
              error: !rule
            };
          }
          return updated;
        });
      } else {
        setConditionsWithDetails((prev) => {
          const updated = [...prev];
          if (updated[index]) {
            updated[index] = {
              ...updated[index],
              ruleName: ruleId,
              loading: false,
              error: true
            };
          }
          return updated;
        });
      }
    } catch (err) {
      logger.error("Failed to fetch rule details", { ruleId, err });
      setConditionsWithDetails((prev) => {
        const updated = [...prev];
        if (updated[index]) {
          updated[index] = {
            ...updated[index],
            ruleName: ruleId,
            loading: false,
            error: true
          };
        }
        return updated;
      });
    }
  };
  const addCondition = (ruleId, _rule) => {
    const newCondition = {
      ruleId,
      required: true,
      validationMessage: { en: "" }
    };
    updateValue([...conditions, newCondition]);
    setIsModalOpen(false);
  };
  const updateCondition = (index, updates) => {
    const updated = [...conditions];
    updated[index] = { ...updated[index], ...updates };
    updateValue(updated);
  };
  const removeCondition = (index) => {
    updateValue(conditions.filter((_, i) => i !== index));
  };
  const moveCondition = (index, direction) => {
    const newIndex = direction === "up" ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= conditions.length) return;
    const updated = [...conditions];
    const temp = updated[index];
    updated[index] = updated[newIndex];
    updated[newIndex] = temp;
    updateValue(updated);
  };
  const getExcludedRuleIds = () => {
    return conditions.map((c) => c.ruleId);
  };
  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__ */ jsx("div", { children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("workflows.fieldEditors.preConditions.description") }) }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          onClick: () => setIsModalOpen(true),
          variant: "outline",
          size: "sm",
          disabled,
          className: "w-full sm:w-auto",
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-1" }),
            t("workflows.fieldEditors.preConditions.addRule")
          ]
        }
      )
    ] }),
    conditions.length === 0 && /* @__PURE__ */ jsx(
      EmptyState,
      {
        title: t("workflows.fieldEditors.preConditions.emptyTitle"),
        description: t("workflows.fieldEditors.preConditions.emptyDescription"),
        action: { label: t("workflows.fieldEditors.preConditions.addRule"), onClick: () => setIsModalOpen(true), disabled }
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: conditionsWithDetails.map((condition, index) => /* @__PURE__ */ jsx("div", { className: "border border-gray-200 rounded-lg bg-white p-4", 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__ */ jsx("div", { className: "flex-1 min-w-0", children: condition.loading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Spinner, { size: "sm" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: t("workflows.common.loadingDetails") })
        ] }) : condition.error ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(AlertCircle, { className: "size-4 text-amber-600" }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: condition.ruleId }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-amber-600", children: t("workflows.common.ruleNotFound") })
          ] })
        ] }) : /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: condition.ruleName }),
            condition.ruleType && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: condition.ruleType })
          ] }),
          /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-0.5", children: [
            "ID: ",
            /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded font-mono", children: condition.ruleId })
          ] })
        ] }) }),
        /* @__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: () => moveCondition(index, "up"),
              disabled: index === 0 || disabled,
              title: t("workflows.common.moveUp"),
              children: /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => moveCondition(index, "down"),
              disabled: index === conditions.length - 1 || disabled,
              title: t("workflows.common.moveDown"),
              children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            ConfirmDialog,
            {
              trigger: /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  title: t("workflows.common.delete"),
                  disabled,
                  children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-red-600" })
                }
              ),
              title: t("workflows.fieldEditors.preConditions.removePreCondition"),
              text: t("workflows.fieldEditors.preConditions.confirmRemove"),
              variant: "destructive",
              onConfirm: () => removeCondition(index)
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsx(
        SwitchField,
        {
          id: `precondition-${index}-required`,
          label: t("workflows.fieldEditors.preConditions.requiredLabel"),
          flip: true,
          checked: conditions[index]?.required ?? true,
          onCheckedChange: (checked) => updateCondition(index, { required: checked }),
          disabled
        }
      ),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: `precondition-${index}-messages`, className: "text-xs", children: t("workflows.fieldEditors.preConditions.validationMessages") }),
        /* @__PURE__ */ jsx(
          LocalizedMessageTextarea,
          {
            id: `precondition-${index}-messages`,
            value: conditions[index]?.validationMessage,
            onChange: (messages) => updateCondition(index, { validationMessage: messages }),
            disabled,
            placeholder: t("workflows.fieldEditors.preConditions.validationMessagesPlaceholder"),
            hint: t("workflows.fieldEditors.preConditions.validationMessagesHint")
          }
        )
      ] })
    ] }) }, index)) }),
    /* @__PURE__ */ jsx(
      BusinessRulesSelector,
      {
        isOpen: isModalOpen,
        onClose: () => setIsModalOpen(false),
        onSelect: addCondition,
        excludeRuleIds: getExcludedRuleIds(),
        title: t("workflows.fieldEditors.preConditions.selectBusinessRule"),
        description: t("workflows.fieldEditors.preConditions.selectBusinessRuleDescription"),
        filterRuleType: "GUARD",
        onlyEnabled: true
      }
    )
  ] });
}
export {
  StartPreConditionsEditor
};
//# sourceMappingURL=StartPreConditionsEditor.js.map
