"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect } 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 { Plus, Trash2, AlertCircle } 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 normalizeCondition(raw) {
  if (typeof raw === "string") {
    return { ruleId: raw, required: true };
  }
  return raw;
}
function BusinessRuleConditionsEditor({
  id,
  value = [],
  setValue,
  disabled,
  filterEntityType,
  filterRuleType
}) {
  const t = useT();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [conditionsWithDetails, setConditionsWithDetails] = useState([]);
  const conditions = Array.isArray(value) ? value : [];
  useEffect(() => {
    const normalized = conditions.map(normalizeCondition);
    const withDetails = normalized.map((c) => ({
      ...c,
      loading: true
    }));
    setConditionsWithDetails(withDetails);
    normalized.forEach((condition, index) => {
      fetchRuleDetails(condition.ruleId, index);
    });
  }, [JSON.stringify(conditions.map(normalizeCondition))]);
  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 };
    setValue([...conditions, newCondition]);
    setIsModalOpen(false);
  };
  const removeCondition = (index) => {
    const newConditions = conditions.filter((_, i) => i !== index);
    setValue(newConditions);
  };
  const toggleRequired = (index) => {
    const normalized = normalizeCondition(conditions[index]);
    const updated = [...conditions];
    updated[index] = {
      ruleId: normalized.ruleId,
      required: !normalized.required
    };
    setValue(updated);
  };
  const getExcludedRuleIds = () => {
    return conditions.map((c) => normalizeCondition(c).ruleId);
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end", children: /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        size: "sm",
        onClick: () => setIsModalOpen(true),
        disabled,
        children: [
          /* @__PURE__ */ jsx(Plus, { className: "size-3 mr-1" }),
          t("workflows.fieldEditors.businessRuleConditions.addRule")
        ]
      }
    ) }),
    conditions.length === 0 ? /* @__PURE__ */ jsx(
      EmptyState,
      {
        title: t("workflows.fieldEditors.businessRuleConditions.emptyTitle"),
        description: t("workflows.fieldEditors.businessRuleConditions.emptyDescription"),
        action: { label: t("workflows.fieldEditors.businessRuleConditions.addRule"), onClick: () => setIsModalOpen(true), disabled }
      }
    ) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: conditionsWithDetails.map((condition, index) => {
      const normalized = normalizeCondition(conditions[index]);
      return /* @__PURE__ */ jsx("div", { className: "border border-gray-200 rounded-lg bg-white p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 space-y-2", children: [
          /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: condition.loading ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(Spinner, { size: "sm" }),
            /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: t("workflows.common.loadingDetails") })
          ] }) : condition.error ? /* @__PURE__ */ jsxs(Fragment, { 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__ */ jsx("span", { className: "text-sm font-semibold text-foreground", children: condition.ruleName }),
            condition.ruleType && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs ml-2", 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__ */ jsx(
            SwitchField,
            {
              id: `${id}-${index}-required`,
              label: t("workflows.fieldEditors.businessRuleConditions.requiredLabel"),
              flip: true,
              checked: normalized.required,
              onCheckedChange: () => toggleRequired(index),
              disabled
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          ConfirmDialog,
          {
            trigger: /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "ghost",
                size: "sm",
                disabled,
                className: "ml-2 flex-shrink-0",
                children: /* @__PURE__ */ jsx(Trash2, { className: "size-4 text-red-600" })
              }
            ),
            title: t("workflows.fieldEditors.businessRuleConditions.removeCondition"),
            text: t("workflows.fieldEditors.businessRuleConditions.confirmRemove"),
            variant: "destructive",
            onConfirm: () => removeCondition(index)
          }
        )
      ] }) }, index);
    }) }),
    /* @__PURE__ */ jsx(
      BusinessRulesSelector,
      {
        isOpen: isModalOpen,
        onClose: () => setIsModalOpen(false),
        onSelect: addCondition,
        excludeRuleIds: getExcludedRuleIds(),
        title: t("workflows.fieldEditors.businessRuleConditions.selectBusinessRule"),
        description: t("workflows.fieldEditors.businessRuleConditions.selectBusinessRuleDescription"),
        filterEntityType,
        filterRuleType,
        onlyEnabled: true
      }
    )
  ] });
}
export {
  BusinessRuleConditionsEditor
};
//# sourceMappingURL=BusinessRuleConditionsEditor.js.map
