"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, Workflow } from "lucide-react";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function WorkflowSelector({
  isOpen,
  onClose,
  onSelect,
  excludeWorkflowIds = [],
  title = "Select Workflow",
  description = "Choose a workflow to invoke as a sub-workflow",
  onlyEnabled = true,
  emptyMessage,
  searchPlaceholder = "Search by workflow ID, name, or description..."
}) {
  const [workflows, setWorkflows] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  useEffect(() => {
    if (isOpen) {
      fetchWorkflows();
    }
  }, [isOpen]);
  const fetchWorkflows = async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      params.set("limit", "50");
      if (onlyEnabled) {
        params.set("enabled", "true");
      }
      const url = `/api/workflows/definitions?${params.toString()}`;
      const response = await apiFetch(url);
      if (response.ok) {
        const result = await response.json();
        setWorkflows(result.data || []);
      } else {
        let errorMessage = `Failed to load workflows (${response.status})`;
        try {
          const errorData = await response.json();
          if (errorData.error) {
            errorMessage = errorData.error;
          }
        } catch {
        }
        logger.error("Failed to fetch workflows", {
          url,
          status: response.status,
          message: errorMessage
        });
        setError(errorMessage);
      }
    } catch (err) {
      logger.error("Failed to fetch workflows", { err });
      const errorMessage = err instanceof Error ? err.message : "Network error loading workflows";
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  const getFilteredWorkflows = () => {
    return workflows.filter((wf) => !excludeWorkflowIds.includes(wf.workflowId)).filter((wf) => {
      if (!searchQuery) return true;
      const query = searchQuery.toLowerCase();
      return wf.workflowName.toLowerCase().includes(query) || wf.workflowId.toLowerCase().includes(query) || wf.description?.toLowerCase().includes(query);
    });
  };
  const handleSelect = (workflow) => {
    onSelect(workflow.workflowId, workflow);
    setSearchQuery("");
  };
  const handleClose = () => {
    setSearchQuery("");
    onClose();
  };
  const filteredWorkflows = getFilteredWorkflows();
  return /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: handleClose, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-4xl 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 workflows..." })
    ] }) : 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: fetchWorkflows,
          children: "Retry"
        }
      )
    ] }) : filteredWorkflows.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12", children: [
      /* @__PURE__ */ jsx(Workflow, { className: "w-16 h-16 text-muted mb-4" }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm mb-2", children: emptyMessage || (searchQuery ? "No workflows found matching your search" : workflows.length === 0 ? "No workflows exist yet" : "All workflows have already been excluded") }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs mb-3", children: workflows.length === 0 ? "Create workflows in the Workflow Definitions page first" : searchQuery ? `Showing 0 of ${workflows.length} total workflows` : `${workflows.length} workflows already excluded` }),
      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: [
        filteredWorkflows.length,
        " workflow",
        filteredWorkflows.length !== 1 ? "s" : "",
        " available"
      ] }),
      /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: filteredWorkflows.map((workflow) => /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => handleSelect(workflow),
          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: workflow.workflowName }),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground font-mono mt-0.5 truncate", children: workflow.workflowId })
              ] }),
              /* @__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__ */ jsxs(Badge, { variant: "secondary", className: "text-xs", children: [
                "v",
                workflow.version
              ] }),
              workflow.enabled ? /* @__PURE__ */ jsx(Badge, { variant: "default", className: "bg-emerald-500 text-xs", children: "Enabled" }) : /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: "Disabled" })
            ] }),
            workflow.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground line-clamp-2", children: workflow.description })
          ]
        },
        workflow.id
      )) })
    ] }) }),
    /* @__PURE__ */ jsx(DialogFooter, { children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "outline",
        onClick: handleClose,
        children: "Cancel"
      }
    ) })
  ] }) });
}
export {
  WorkflowSelector
};
//# sourceMappingURL=WorkflowSelector.js.map
