"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import { apiFetch } from "@open-mercato/ui/backend/utils/api";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@open-mercato/ui/primitives/dialog";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Plus, Loader2, AlertCircle } from "lucide-react";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function BusinessRulesSelector({
  isOpen,
  onClose,
  onSelect,
  excludeRuleIds = [],
  title = "Select Business Rule",
  description = "Choose a business rule from the list",
  filterEntityType,
  filterRuleType,
  filterCategory,
  onlyEnabled = false,
  emptyMessage,
  searchPlaceholder = "Search by name, ID, type, category, or description..."
}) {
  const [businessRules, setBusinessRules] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  useEffect(() => {
    if (isOpen) {
      fetchBusinessRules();
    }
  }, [isOpen]);
  const fetchBusinessRules = async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      params.set("pageSize", "100");
      if (filterEntityType) {
        params.set("entityType", filterEntityType);
      }
      if (filterRuleType) {
        params.set("ruleType", filterRuleType);
      }
      if (filterCategory) {
        params.set("ruleCategory", filterCategory);
      }
      if (onlyEnabled) {
        params.set("enabled", "true");
      }
      const url = `/api/business_rules/rules?${params.toString()}`;
      const response = await apiFetch(url);
      if (response.ok) {
        const data = await response.json();
        setBusinessRules(data.items || []);
      } else {
        let errorMessage = `Failed to load business rules (${response.status})`;
        try {
          const errorData = await response.json();
          if (errorData.error) {
            errorMessage = errorData.error;
          }
        } catch {
          errorMessage = `Failed to load business rules (${response.status})`;
        }
        logger.error("Failed to fetch business rules", {
          url,
          status: response.status,
          message: errorMessage
        });
        setError(errorMessage);
      }
    } catch (err) {
      logger.error("Failed to fetch business rules", { err });
      const errorMessage = err instanceof Error ? err.message : "Network error loading business rules";
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  const getFilteredRules = () => {
    return businessRules.filter((rule) => !excludeRuleIds.includes(rule.ruleId)).filter((rule) => {
      if (!searchQuery) return true;
      const query = searchQuery.toLowerCase();
      return rule.ruleName.toLowerCase().includes(query) || rule.ruleId.toLowerCase().includes(query) || rule.description?.toLowerCase().includes(query) || rule.ruleType.toLowerCase().includes(query) || rule.ruleCategory?.toLowerCase().includes(query) || rule.entityType.toLowerCase().includes(query);
    });
  };
  const handleSelect = (rule) => {
    onSelect(rule.ruleId, rule);
    setSearchQuery("");
  };
  const handleClose = () => {
    setSearchQuery("");
    onClose();
  };
  const filteredRules = getFilteredRules();
  return /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-5xl max-h-[85vh] flex flex-col", children: [
    /* @__PURE__ */ jsxs(DialogHeader, { children: [
      /* @__PURE__ */ jsx(DialogTitle, { children: title }),
      /* @__PURE__ */ jsx(DialogDescription, { children: description })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "px-6", children: /* @__PURE__ */ jsx(
      Input,
      {
        type: "text",
        value: searchQuery,
        onChange: (e) => setSearchQuery(e.target.value),
        placeholder: searchPlaceholder,
        autoFocus: true,
        disabled: loading
      }
    ) }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto px-6 py-4 min-h-[400px]", children: loading ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12", children: [
      /* @__PURE__ */ jsx(Loader2, { className: "h-12 w-12 animate-spin text-primary mb-4" }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: "Loading business rules..." })
    ] }) : error ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12", children: [
      /* @__PURE__ */ jsx(AlertCircle, { className: "h-16 w-16 text-destructive mb-4" }),
      /* @__PURE__ */ jsx("p", { className: "text-destructive text-sm font-medium mb-2", children: error }),
      /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: fetchBusinessRules,
          children: "Retry"
        }
      )
    ] }) : filteredRules.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12", children: [
      /* @__PURE__ */ jsx("svg", { className: "w-16 h-16 text-muted mb-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" }) }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm mb-2", children: emptyMessage || (searchQuery ? "No business rules found matching your search" : businessRules.length === 0 ? "No business rules exist yet" : "All business rules have already been added") }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs mb-3", children: businessRules.length === 0 ? "Create business rules in the Business Rules module first" : searchQuery ? `Showing 0 of ${businessRules.length} total rules` : `${businessRules.length} rules already added` }),
      searchQuery && /* @__PURE__ */ jsx(
        Button,
        {
          variant: "link",
          size: "sm",
          onClick: () => setSearchQuery(""),
          children: "Clear search"
        }
      )
    ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs("div", { className: "mb-3 text-sm text-muted-foreground", children: [
        filteredRules.length,
        " rule",
        filteredRules.length !== 1 ? "s" : "",
        " available"
      ] }),
      /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: filteredRules.map((rule) => /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => handleSelect(rule),
          className: "text-left p-4 border-2 border-border rounded-lg hover:border-primary hover:bg-accent transition-all group",
          children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between mb-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
                /* @__PURE__ */ jsx("h4", { className: "text-sm font-semibold group-hover:text-primary truncate", children: rule.ruleName }),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground font-mono mt-0.5 truncate", children: rule.ruleId })
              ] }),
              /* @__PURE__ */ jsx(Plus, { className: "size-5 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0 ml-2" })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2 flex-wrap", children: [
              /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: rule.ruleType }),
              rule.ruleCategory && /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: rule.ruleCategory }),
              rule.enabled ? /* @__PURE__ */ jsx(Badge, { variant: "default", className: "bg-emerald-500 text-xs", children: "Enabled" }) : /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: "Disabled" })
            ] }),
            rule.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground line-clamp-2 mb-2", children: rule.description }),
            /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground space-y-0.5", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsx("span", { className: "font-medium", children: "Entity:" }),
                /* @__PURE__ */ jsx("span", { className: "font-mono text-xs", children: rule.entityType })
              ] }),
              rule.eventType && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsx("span", { className: "font-medium", children: "Event:" }),
                /* @__PURE__ */ jsx("span", { children: rule.eventType })
              ] })
            ] })
          ]
        },
        rule.id
      )) })
    ] }) }),
    /* @__PURE__ */ jsx(DialogFooter, { children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "outline",
        onClick: handleClose,
        children: "Cancel"
      }
    ) })
  ] }) });
}
export {
  BusinessRulesSelector
};
//# sourceMappingURL=BusinessRulesSelector.js.map
