"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 { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
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 { Search, X, Loader2, AlertCircle, Workflow } from "lucide-react";
import { WorkflowSelector } from "../WorkflowSelector.js";
import { apiFetch } from "@open-mercato/ui/backend/utils/api";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function WorkflowSelectorField({
  id,
  value = "",
  error,
  setValue,
  disabled,
  label: labelProp,
  description: descriptionProp
}) {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const label = labelProp ?? t("workflows.fieldEditors.workflowSelector.label");
  const description = descriptionProp ?? t("workflows.fieldEditors.workflowSelector.description");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [workflowDetails, setWorkflowDetails] = useState(null);
  const workflowId = value || "";
  useEffect(() => {
    if (workflowId) {
      setWorkflowDetails({ workflowId, loading: true });
      fetchWorkflowDetails(workflowId);
    } else {
      setWorkflowDetails(null);
    }
  }, [workflowId]);
  const fetchWorkflowDetails = async (wfId) => {
    try {
      const params = new URLSearchParams({ workflowId: wfId, limit: "1" });
      const response = await apiFetch(`/api/workflows/definitions?${params.toString()}`);
      if (response.ok) {
        const result = await response.json();
        const workflow = result.data?.[0];
        setWorkflowDetails({
          workflowId: wfId,
          workflowName: workflow?.workflowName,
          version: workflow?.version,
          enabled: workflow?.enabled,
          description: workflow?.description,
          loading: false,
          error: !workflow
        });
      } else {
        setWorkflowDetails({
          workflowId: wfId,
          loading: false,
          error: true
        });
      }
    } catch (err) {
      logger.error("Failed to fetch workflow details", { workflowId: wfId, err });
      setWorkflowDetails({
        workflowId: wfId,
        loading: false,
        error: true
      });
    }
  };
  const handleSelect = (selectedWorkflowId, _workflow) => {
    setValue(selectedWorkflowId);
    setIsModalOpen(false);
  };
  const handleClear = async () => {
    const confirmed = await confirm({
      title: t("workflows.common.clear"),
      text: t("workflows.fieldEditors.workflowSelector.confirmClear"),
      variant: "default"
    });
    if (!confirmed) return;
    setValue("");
    setWorkflowDetails(null);
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx(Label, { htmlFor: id, className: "text-sm font-medium", children: label }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-0.5", children: description }),
      error && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600 mt-1", children: error })
    ] }),
    !workflowId ? (
      /* No Workflow Selected */
      /* @__PURE__ */ jsxs("div", { className: "border-2 border-dashed border-gray-300 rounded-lg p-6 text-center", children: [
        /* @__PURE__ */ jsx(Workflow, { className: "size-8 text-muted-foreground mx-auto mb-2" }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mb-3", children: t("workflows.fieldEditors.workflowSelector.noWorkflowSelected") }),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            size: "sm",
            onClick: () => setIsModalOpen(true),
            disabled,
            children: [
              /* @__PURE__ */ jsx(Search, { className: "size-3 mr-1" }),
              t("workflows.fieldEditors.workflowSelector.browseWorkflows")
            ]
          }
        )
      ] })
    ) : (
      /* Workflow Selected */
      /* @__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__ */ jsx("div", { className: "flex-1 min-w-0 space-y-2", children: workflowDetails?.loading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin text-muted-foreground" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: t("workflows.common.loadingDetails") })
        ] }) : workflowDetails?.error ? /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(AlertCircle, { className: "size-4 text-yellow-600" }),
            /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-gray-900", children: workflowId })
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-yellow-600", children: t("workflows.common.workflowNotFoundOrUnavailable") })
        ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-gray-900", children: workflowDetails?.workflowName || workflowId }),
              workflowDetails?.version !== void 0 && /* @__PURE__ */ jsxs(Badge, { variant: "secondary", className: "text-xs", children: [
                "v",
                workflowDetails.version
              ] }),
              workflowDetails?.enabled !== void 0 && (workflowDetails.enabled ? /* @__PURE__ */ jsx(Badge, { variant: "default", className: "bg-emerald-500 text-xs", children: t("common.enabled") }) : /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "text-xs", children: t("common.disabled") }))
            ] }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground font-mono mt-0.5", children: workflowId })
          ] }),
          workflowDetails?.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: workflowDetails.description })
        ] }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 ml-4 flex-shrink-0", children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: () => setIsModalOpen(true),
              disabled,
              children: [
                /* @__PURE__ */ jsx(Search, { className: "size-3 mr-1" }),
                t("workflows.common.change")
              ]
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: handleClear,
              disabled,
              children: /* @__PURE__ */ jsx(X, { className: "size-4" })
            }
          )
        ] })
      ] }) })
    ),
    /* @__PURE__ */ jsx(
      WorkflowSelector,
      {
        isOpen: isModalOpen,
        onClose: () => setIsModalOpen(false),
        onSelect: handleSelect,
        excludeWorkflowIds: workflowId ? [workflowId] : [],
        title: t("workflows.fieldEditors.workflowSelector.selectSubWorkflow"),
        description: t("workflows.fieldEditors.workflowSelector.selectSubWorkflowDescription"),
        onlyEnabled: true
      }
    ),
    ConfirmDialogElement
  ] });
}
export {
  WorkflowSelectorField
};
//# sourceMappingURL=WorkflowSelectorField.js.map
