"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Plus, ChevronUp, ChevronDown, X } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function RuleSetMembers({ members, onAdd, onUpdate, onRemove }) {
  const t = useT();
  const [showAddForm, setShowAddForm] = React.useState(false);
  const [selectedRuleId, setSelectedRuleId] = React.useState("");
  const [sequence, setSequence] = React.useState(0);
  const { data: availableRules } = useQuery({
    queryKey: ["business-rules", "rules-list"],
    queryFn: async () => {
      const result = await apiCall(
        "/api/business_rules/rules?page=1&pageSize=100&sortField=ruleName&sortDir=asc"
      );
      if (!result.ok) {
        throw new Error("Failed to fetch rules");
      }
      return result.result?.items || [];
    }
  });
  const rulesNotInSet = React.useMemo(() => {
    const memberRuleIds = new Set(members.map((m) => m.ruleId));
    return availableRules?.filter((r) => !memberRuleIds.has(r.id)) || [];
  }, [members, availableRules]);
  const handleAdd = async () => {
    if (!selectedRuleId) return;
    await onAdd(selectedRuleId, sequence);
    setSelectedRuleId("");
    setSequence(0);
    setShowAddForm(false);
  };
  const handleMoveUp = async (member, index) => {
    if (index === 0) return;
    const prevMember = members[index - 1];
    await onUpdate(member.id, { sequence: prevMember.sequence });
    await onUpdate(prevMember.id, { sequence: member.sequence });
  };
  const handleMoveDown = async (member, index) => {
    if (index === members.length - 1) return;
    const nextMember = members[index + 1];
    await onUpdate(member.id, { sequence: nextMember.sequence });
    await onUpdate(nextMember.id, { sequence: member.sequence });
  };
  const handleToggleEnabled = async (member) => {
    await onUpdate(member.id, { enabled: !member.enabled });
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    members.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-center py-8 text-muted-foreground", children: /* @__PURE__ */ jsx("p", { children: t("business_rules.sets.members.empty") }) }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: members.map((member, index) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "flex items-center gap-3 p-3 bg-muted rounded border border-border",
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
            /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => handleMoveUp(member, index),
                disabled: index === 0,
                className: "p-1 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed",
                title: t("common.moveUp"),
                children: /* @__PURE__ */ jsx(ChevronUp, { className: "w-4 h-4" })
              }
            ),
            /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => handleMoveDown(member, index),
                disabled: index === members.length - 1,
                className: "p-1 text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed",
                title: t("common.moveDown"),
                children: /* @__PURE__ */ jsx(ChevronDown, { className: "w-4 h-4" })
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center w-8 h-8 bg-status-info-bg text-status-info-text rounded font-mono text-sm font-medium", children: member.sequence }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsx("div", { className: "font-medium", children: member.ruleName }),
            /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground font-mono", children: member.ruleId })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "px-2 py-1 bg-muted text-muted-foreground text-xs rounded font-medium", children: member.ruleType }),
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => handleToggleEnabled(member),
              className: `px-2 py-1 rounded text-xs font-medium cursor-pointer ${member.enabled ? "bg-status-success-bg text-status-success-text hover:bg-status-success-bg/80" : "bg-muted text-muted-foreground hover:bg-muted/50"}`,
              title: t("business_rules.sets.members.actions.toggleEnabled"),
              children: member.enabled ? t("common.enabled") : t("common.disabled")
            }
          ),
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => onRemove(member.id, member.ruleName),
              className: "p-1.5 text-muted-foreground hover:text-status-error-text hover:bg-status-error-bg rounded transition-colors",
              title: t("common.remove"),
              children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" })
            }
          )
        ]
      },
      member.id
    )) }),
    showAddForm ? /* @__PURE__ */ jsxs("div", { className: "p-4 bg-status-info-bg border border-status-info-border rounded space-y-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
          /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-foreground mb-1", children: t("business_rules.sets.members.form.selectRule") }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: selectedRuleId || void 0,
              onValueChange: (value) => setSelectedRuleId(value ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("business_rules.sets.members.form.selectRulePlaceholder") }) }),
                /* @__PURE__ */ jsx(SelectContent, { children: rulesNotInSet.map((rule) => /* @__PURE__ */ jsxs(SelectItem, { value: rule.id, children: [
                  rule.ruleName,
                  " (",
                  rule.ruleId,
                  ")"
                ] }, rule.id)) })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "w-32", children: [
          /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-foreground mb-1", children: t("business_rules.sets.members.form.sequence") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              value: sequence,
              onChange: (e) => setSequence(parseInt(e.target.value) || 0),
              min: 0
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(Button, { onClick: handleAdd, disabled: !selectedRuleId, size: "sm", children: t("business_rules.sets.members.actions.add") }),
        /* @__PURE__ */ jsx(
          Button,
          {
            onClick: () => {
              setShowAddForm(false);
              setSelectedRuleId("");
              setSequence(0);
            },
            variant: "outline",
            size: "sm",
            children: t("common.cancel")
          }
        )
      ] })
    ] }) : /* @__PURE__ */ jsxs(Button, { onClick: () => setShowAddForm(true), variant: "outline", size: "sm", children: [
      /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 mr-2" }),
      t("business_rules.sets.members.actions.addRule")
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground space-y-1", children: [
      /* @__PURE__ */ jsxs("p", { children: [
        /* @__PURE__ */ jsxs("strong", { children: [
          t("business_rules.sets.members.help.ordering"),
          ":"
        ] }),
        " ",
        t("business_rules.sets.members.help.orderingDescription")
      ] }),
      /* @__PURE__ */ jsxs("p", { children: [
        /* @__PURE__ */ jsxs("strong", { children: [
          t("business_rules.sets.members.help.enabled"),
          ":"
        ] }),
        " ",
        t("business_rules.sets.members.help.enabledDescription")
      ] })
    ] })
  ] });
}
export {
  RuleSetMembers
};
//# sourceMappingURL=RuleSetMembers.js.map
