"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { emitSalesDocumentDataRefresh } from "@open-mercato/core/modules/sales/lib/frontend/documentDataEvents";
const WORKFLOW_ID = "sales.order-approval";
function OrderApprovalWidget({ data }) {
  const t = useT();
  const queryClient = useQueryClient();
  const orderId = data?.id;
  const [decision, setDecision] = React.useState("");
  const [comments, setComments] = React.useState("");
  const [error, setError] = React.useState(null);
  const [isWaitingForProcessing, setIsWaitingForProcessing] = React.useState(false);
  const { data: orderData } = useQuery({
    queryKey: ["order-status", orderId],
    queryFn: async () => {
      if (!orderId) return null;
      const result = await apiCall(
        `/api/sales/orders?id=${orderId}&pageSize=1`
      );
      return result.ok && result.result?.items?.[0] ? result.result.items[0] : null;
    },
    enabled: Boolean(orderId),
    staleTime: 5e3,
    // Poll when waiting for processing to detect status change
    refetchInterval: isWaitingForProcessing ? 2e3 : false
  });
  const currentOrderStatus = orderData?.status || data?.status;
  const { data: instancesData, isLoading: instancesLoading } = useQuery({
    queryKey: ["workflow-instances", orderId],
    queryFn: async () => {
      if (!orderId) return { data: [] };
      const result = await apiCall(
        `/api/workflows/instances?entityId=${orderId}&status=RUNNING,PAUSED,WAITING_FOR_ACTIVITIES`
      );
      return result.ok ? result.result : { data: [] };
    },
    enabled: Boolean(orderId),
    staleTime: 5e3,
    // Poll every 2 seconds when waiting for processing
    refetchInterval: isWaitingForProcessing ? 2e3 : false
  });
  const activeInstance = instancesData?.data?.find(
    (inst) => inst.workflowId === WORKFLOW_ID && !["COMPLETED", "FAILED", "CANCELLED"].includes(inst.status)
  );
  const { data: tasksData, isLoading: tasksLoading } = useQuery({
    queryKey: ["workflow-tasks", activeInstance?.id],
    queryFn: async () => {
      if (!activeInstance?.id) return { data: [] };
      const result = await apiCall(
        `/api/workflows/tasks?workflowInstanceId=${activeInstance.id}&status=PENDING,IN_PROGRESS`
      );
      return result.ok ? result.result : { data: [] };
    },
    enabled: Boolean(activeInstance?.id),
    staleTime: 5e3,
    // Poll every 2 seconds when waiting for processing
    refetchInterval: isWaitingForProcessing ? 2e3 : false
  });
  const pendingTask = tasksData?.data?.[0];
  const isProcessing = activeInstance && !pendingTask && !["COMPLETED", "FAILED", "CANCELLED"].includes(activeInstance.status);
  const prevStatusRef = React.useRef(data?.status);
  React.useEffect(() => {
    if (isProcessing) {
      setIsWaitingForProcessing(true);
    } else if (!activeInstance || activeInstance.status === "COMPLETED") {
      setIsWaitingForProcessing(false);
    }
  }, [isProcessing, activeInstance]);
  React.useEffect(() => {
    const newStatus = orderData?.status;
    const oldStatus = prevStatusRef.current;
    if (newStatus && oldStatus && newStatus !== oldStatus) {
      if (orderId) {
        emitSalesDocumentDataRefresh({ documentId: orderId, kind: "order" });
      }
    }
    prevStatusRef.current = newStatus || oldStatus;
  }, [orderData?.status, orderId]);
  const { data: dictionariesData } = useQuery({
    queryKey: ["dictionaries"],
    queryFn: async () => {
      const result = await apiCall(
        "/api/dictionaries"
      );
      return result.ok ? result.result : { items: [] };
    },
    staleTime: 6e4
  });
  const orderStatusDictionaryId = React.useMemo(() => {
    const dict = dictionariesData?.items?.find((d) => d.key === "sales.order_status");
    return dict?.id;
  }, [dictionariesData]);
  const { data: statusEntriesData } = useQuery({
    queryKey: ["dictionary-entries", orderStatusDictionaryId],
    queryFn: async () => {
      if (!orderStatusDictionaryId) return { items: [] };
      const result = await apiCall(
        `/api/dictionaries/${orderStatusDictionaryId}/entries`
      );
      return result.ok ? result.result : { items: [] };
    },
    enabled: Boolean(orderStatusDictionaryId),
    staleTime: 6e4
  });
  const findStatusId = React.useCallback((code) => {
    const entries = statusEntriesData?.items || [];
    const entry = entries.find(
      (e) => e.value === code || e.label?.toLowerCase() === code.toLowerCase()
    );
    return entry?.id;
  }, [statusEntriesData]);
  const startWorkflowMutation = useMutation({
    mutationFn: async () => {
      const pendingApprovalStatusId = findStatusId("pending_approval");
      const approvedStatusId = findStatusId("approved");
      const rejectedStatusId = findStatusId("rejected");
      if (!pendingApprovalStatusId || !approvedStatusId || !rejectedStatusId) {
        throw new Error(t("workflows.orderApproval.missingStatuses", "Missing order status entries. Please ensure pending_approval, approved, and rejected statuses exist in the sales.order_status dictionary."));
      }
      const result = await apiCall("/api/workflows/instances", {
        method: "POST",
        body: JSON.stringify({
          workflowId: WORKFLOW_ID,
          initialContext: {
            orderId,
            pendingApprovalStatusId,
            approvedStatusId,
            rejectedStatusId
          },
          metadata: {
            entityType: "SalesOrder",
            entityId: orderId
          }
        })
      });
      if (!result.ok) {
        const errorResult = result.result;
        throw new Error(errorResult?.error || t("workflows.orderApproval.startError", "Failed to start approval workflow"));
      }
      return result.result;
    },
    onSuccess: () => {
      setError(null);
      queryClient.invalidateQueries({ queryKey: ["workflow-instances", orderId] });
    },
    onError: (err) => {
      setError(err.message);
    }
  });
  const completeTaskMutation = useMutation({
    mutationFn: async ({ taskId, formData }) => {
      const result = await apiCall(`/api/workflows/tasks/${taskId}/complete`, {
        method: "POST",
        body: JSON.stringify({ formData })
      });
      if (!result.ok) {
        const errorResult = result.result;
        throw new Error(errorResult?.error || t("workflows.orderApproval.completeError", "Failed to complete approval task"));
      }
      return result.result;
    },
    onSuccess: () => {
      setError(null);
      setDecision("");
      setComments("");
      setIsWaitingForProcessing(true);
      queryClient.invalidateQueries({ queryKey: ["workflow-instances", orderId] });
      queryClient.invalidateQueries({ queryKey: ["workflow-tasks", activeInstance?.id] });
      queryClient.invalidateQueries({ queryKey: ["sales-order", orderId] });
    },
    onError: (err) => {
      setError(err.message);
    }
  });
  const handleStartWorkflow = () => {
    setIsWaitingForProcessing(true);
    startWorkflowMutation.mutate();
  };
  const handleCompleteTask = () => {
    if (!pendingTask || !decision) return;
    completeTaskMutation.mutate({
      taskId: pendingTask.id,
      formData: { decision, comments }
    });
  };
  const handleKeyDown = (e) => {
    if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
      e.preventDefault();
      if (pendingTask && decision && !isSubmitting) {
        handleCompleteTask();
      }
    }
  };
  const isLoading = instancesLoading || tasksLoading;
  const isSubmitting = startWorkflowMutation.isPending || completeTaskMutation.isPending;
  if (!orderId) return null;
  const orderStatus = currentOrderStatus?.toLowerCase();
  if (orderStatus !== "pending_approval") {
    return null;
  }
  if (isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center p-4", children: [
      /* @__PURE__ */ jsx(Spinner, { size: "sm" }),
      /* @__PURE__ */ jsx("span", { className: "ml-2 text-sm text-muted-foreground", children: t("common.loading", "Loading...") })
    ] });
  }
  const getStatusBadge = () => {
    if (!activeInstance) return null;
    const statusVariants = {
      RUNNING: "default",
      PAUSED: "secondary",
      WAITING_FOR_ACTIVITIES: "secondary",
      COMPLETED: "default",
      FAILED: "destructive",
      CANCELLED: "outline"
    };
    return /* @__PURE__ */ jsx(Badge, { variant: statusVariants[activeInstance.status] || "outline", children: t(`workflows.instances.statuses.${activeInstance.status}`, activeInstance.status) });
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded-lg border bg-card p-4 shadow-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: t("workflows.orderApproval.groupLabel", "Order Approval") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("workflows.orderApproval.groupDescription", "Review and approve or reject this order") })
      ] }),
      getStatusBadge()
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-800", children: error }),
    !activeInstance && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("workflows.orderApproval.noWorkflowActive", "No approval workflow is active for this order.") }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          onClick: handleStartWorkflow,
          disabled: isSubmitting,
          variant: "default",
          size: "sm",
          children: [
            isSubmitting && /* @__PURE__ */ jsx(Spinner, { size: "sm", className: "mr-2" }),
            t("workflows.orderApproval.requestApproval", "Request Approval")
          ]
        }
      )
    ] }),
    activeInstance && pendingTask && /* @__PURE__ */ jsxs("div", { className: "space-y-3", onKeyDown: handleKeyDown, children: [
      /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-amber-200 bg-amber-50 p-3", children: [
        /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-amber-800", children: t("workflows.orderApproval.pendingTitle", "Pending Approval") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-amber-700 mt-1", children: t("workflows.orderApproval.pendingDescription", "This order requires approval before processing.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium", children: t("workflows.orderApproval.decisionLabel", "Decision") }),
        /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: decision === "approve" ? "default" : "outline",
              size: "sm",
              onClick: () => setDecision("approve"),
              className: decision === "approve" ? "bg-emerald-600 hover:bg-emerald-700" : "",
              children: t("workflows.orderApproval.approveButton", "Approve")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: decision === "reject" ? "destructive" : "outline",
              size: "sm",
              onClick: () => setDecision("reject"),
              children: t("workflows.orderApproval.rejectButton", "Reject")
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxs("label", { className: "text-sm font-medium", children: [
          t("workflows.orderApproval.commentsLabel", "Comments"),
          " ",
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-normal", children: [
            "(",
            t("common.optional", "optional"),
            ")"
          ] })
        ] }),
        /* @__PURE__ */ jsx(
          Textarea,
          {
            value: comments,
            onChange: (e) => setComments(e.target.value),
            placeholder: t("workflows.orderApproval.commentsPlaceholder", "Add optional comments..."),
            rows: 2
          }
        )
      ] }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          onClick: handleCompleteTask,
          disabled: !decision || isSubmitting,
          variant: "default",
          size: "sm",
          className: "w-full",
          children: [
            isSubmitting && /* @__PURE__ */ jsx(Spinner, { size: "sm", className: "mr-2" }),
            t("workflows.orderApproval.submitDecision", "Submit Decision")
          ]
        }
      )
    ] }),
    activeInstance && !pendingTask && activeInstance.status !== "COMPLETED" && /* @__PURE__ */ jsx("div", { className: "rounded-md border border-blue-200 bg-blue-50 p-3", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-blue-800", children: t("workflows.orderApproval.processing", "Workflow is processing...") }) }),
    activeInstance && activeInstance.status === "COMPLETED" && /* @__PURE__ */ jsx("div", { className: "rounded-md border border-emerald-200 bg-emerald-50 p-3", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-emerald-800", children: t("workflows.orderApproval.completed", "Approval workflow completed.") }) })
  ] });
}
export {
  OrderApprovalWidget as default
};
//# sourceMappingURL=widget.client.js.map
