"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { FormHeader } from "@open-mercato/ui/backend/forms";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { JsonDisplay } from "@open-mercato/ui/backend/JsonDisplay";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiFetch } from "@open-mercato/ui/backend/utils/api";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { WorkflowGraphReadOnly } from "../../../components/WorkflowGraph.js";
import { WorkflowLegend } from "../../../components/WorkflowLegend.js";
import { MobileInstanceOverview } from "../../../components/mobile/MobileInstanceOverview.js";
import { useIsMobile } from "@open-mercato/ui/hooks/useIsMobile";
import { definitionToGraph } from "../../../lib/graph-utils.js";
import { RecordNotFoundState, ErrorMessage } from "@open-mercato/ui/backend/detail";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function WorkflowInstanceDetailPage({ params }) {
  const id = params?.id;
  const t = useT();
  const isMobile = useIsMobile();
  const queryClient = useQueryClient();
  const { confirm: confirmDialog, ConfirmDialogElement } = useConfirmDialog();
  const { data: instance, isLoading, error } = useQuery({
    queryKey: ["workflow-instance", id],
    queryFn: async () => {
      const response = await apiFetch(`/api/workflows/instances/${id}`);
      if (!response.ok) {
        const httpErr = new Error(
          response.status === 404 ? t("workflows.instances.detail.notFound", "Workflow instance not found.") : t("workflows.instances.loadFailed", "Failed to load workflow instance.")
        );
        httpErr.status = response.status;
        throw httpErr;
      }
      const data = await response.json();
      return data.data;
    },
    enabled: !!id
  });
  const { data: events = [], isLoading: eventsLoading } = useQuery({
    queryKey: ["workflow-events", instance?.id],
    queryFn: async () => {
      const response = await apiFetch(
        `/api/workflows/events?workflowInstanceId=${instance.id}&sortField=occurredAt&sortDir=desc&pageSize=100`
      );
      if (!response.ok) {
        throw new Error("Failed to fetch events");
      }
      const data = await response.json();
      return data.items || [];
    },
    enabled: !!instance?.id
  });
  const { data: workflowDefinition, isLoading: definitionLoading } = useQuery({
    queryKey: ["workflow-definition-for-instance", instance?.definitionId],
    queryFn: async () => {
      const response = await apiFetch(`/api/workflows/definitions/${instance.definitionId}`);
      if (!response.ok) {
        logger.error("Failed to fetch workflow definition", { statusText: response.statusText });
        return null;
      }
      const result = await response.json();
      return result.data;
    },
    enabled: !!instance?.definitionId
  });
  const calculateDuration = (startedAt, completedAt) => {
    const start = typeof startedAt === "string" ? new Date(startedAt).getTime() : startedAt.getTime();
    const end = completedAt ? typeof completedAt === "string" ? new Date(completedAt).getTime() : completedAt.getTime() : Date.now();
    const duration = end - start;
    if (duration < 1e3) {
      return `${duration}ms`;
    } else if (duration < 6e4) {
      return `${Math.floor(duration / 1e3)}s`;
    } else if (duration < 36e5) {
      return `${Math.floor(duration / 6e4)}m ${Math.floor(duration % 6e4 / 1e3)}s`;
    } else {
      const hours = Math.floor(duration / 36e5);
      const minutes = Math.floor(duration % 36e5 / 6e4);
      return `${hours}h ${minutes}m`;
    }
  };
  const getStatusBadgeClass = (status) => {
    switch (status) {
      case "RUNNING":
        return "bg-blue-100 text-blue-800";
      case "PAUSED":
        return "bg-yellow-100 text-yellow-800";
      case "WAITING_FOR_ACTIVITIES":
        return "bg-cyan-100 text-cyan-800";
      case "COMPLETED":
        return "bg-green-100 text-green-800";
      case "FAILED":
        return "bg-red-100 text-red-800";
      case "CANCELLED":
        return "bg-muted text-foreground";
      case "COMPENSATING":
        return "bg-orange-100 text-orange-800";
      case "COMPENSATED":
        return "bg-purple-100 text-purple-800";
      default:
        return "bg-muted text-muted-foreground";
    }
  };
  const getEventTypeBadgeClass = (eventType) => {
    if (eventType.includes("COMPENSATION") || eventType.includes("Compensation")) {
      return "bg-orange-100 text-orange-800";
    } else if (eventType.includes("STARTED") || eventType.includes("ENTERED")) {
      return "bg-blue-100 text-blue-800";
    } else if (eventType.includes("COMPLETED") || eventType.includes("EXITED")) {
      return "bg-green-100 text-green-800";
    } else if (eventType.includes("FAILED") || eventType.includes("REJECTED")) {
      return "bg-red-100 text-red-800";
    } else if (eventType.includes("CANCELLED")) {
      return "bg-muted text-foreground";
    } else if (eventType.includes("PAUSED")) {
      return "bg-yellow-100 text-yellow-800";
    } else {
      return "bg-muted text-foreground";
    }
  };
  const cancelMutation = useMutation({
    mutationFn: async () => {
      const response = await apiFetch(`/api/workflows/instances/${instance.id}/cancel`, {
        method: "POST"
      });
      if (!response.ok) {
        throw new Error(t("workflows.instances.cancelFailed"));
      }
      return response.json();
    },
    onSuccess: () => {
      flash(t("workflows.instances.messages.cancelled"), "success");
      queryClient.invalidateQueries({ queryKey: ["workflow-instance", id] });
    },
    onError: (error2) => {
      logger.error("Error cancelling instance", { err: error2 });
      flash(t("workflows.instances.cancelFailed"), "error");
    }
  });
  const retryMutation = useMutation({
    mutationFn: async () => {
      const response = await apiFetch(`/api/workflows/instances/${instance.id}/retry`, {
        method: "POST"
      });
      if (!response.ok) {
        throw new Error(t("workflows.instances.retryFailed"));
      }
      return response.json();
    },
    onSuccess: () => {
      flash(t("workflows.instances.messages.retried"), "success");
      queryClient.invalidateQueries({ queryKey: ["workflow-instance", id] });
    },
    onError: (error2) => {
      logger.error("Error retrying instance", { err: error2 });
      flash(t("workflows.instances.retryFailed"), "error");
    }
  });
  const handleCancel = async () => {
    if (!instance) return;
    const confirmed = await confirmDialog({
      title: t("workflows.instances.confirmCancel"),
      variant: "destructive"
    });
    if (!confirmed) {
      return;
    }
    cancelMutation.mutate();
  };
  const handleRetry = async () => {
    if (!instance) return;
    const confirmed = await confirmDialog({
      title: t("workflows.instances.confirmRetry"),
      variant: "default"
    });
    if (!confirmed) {
      return;
    }
    retryMutation.mutate();
  };
  const { graphNodes, graphEdges } = React.useMemo(() => {
    if (!workflowDefinition?.definition) {
      return { graphNodes: [], graphEdges: [] };
    }
    const { nodes, edges } = definitionToGraph(workflowDefinition.definition, { autoLayout: true });
    const stepStatuses = /* @__PURE__ */ new Map();
    const stepTimings = /* @__PURE__ */ new Map();
    for (const event of events) {
      const stepId = event.eventData?.stepId || event.eventData?.toStepId;
      if (!stepId) continue;
      if (event.eventType === "STEP_ENTERED" || event.eventType === "StepEntered") {
        stepTimings.set(stepId, { ...stepTimings.get(stepId), startedAt: new Date(event.occurredAt) });
        if (!stepStatuses.has(stepId)) {
          stepStatuses.set(stepId, "active");
        }
      } else if (event.eventType === "STEP_COMPLETED" || event.eventType === "STEP_EXITED" || event.eventType === "StepExited") {
        stepTimings.set(stepId, { ...stepTimings.get(stepId), completedAt: new Date(event.occurredAt) });
        stepStatuses.set(stepId, "completed");
      } else if (event.eventType === "STEP_FAILED" || event.eventType === "StepFailed") {
        stepTimings.set(stepId, { ...stepTimings.get(stepId), completedAt: new Date(event.occurredAt) });
        stepStatuses.set(stepId, "failed");
      }
    }
    if (instance?.currentStepId && !stepStatuses.has(instance.currentStepId)) {
      stepStatuses.set(instance.currentStepId, "active");
    } else if (instance?.currentStepId && stepStatuses.get(instance.currentStepId) !== "completed") {
      stepStatuses.set(instance.currentStepId, "active");
    }
    for (const node of nodes) {
      if (!stepStatuses.has(node.id)) {
        const nodeType = node.type;
        const isCurrentStep = instance?.currentStepId === node.id;
        if (nodeType === "start") {
          if (isCurrentStep) {
            stepStatuses.set(node.id, "active");
          } else {
            stepStatuses.set(node.id, "completed");
          }
        } else if (nodeType === "end") {
          if (isCurrentStep || instance?.status === "COMPLETED") {
            stepStatuses.set(node.id, "completed");
          } else {
            stepStatuses.set(node.id, "pending");
          }
        } else {
          stepStatuses.set(node.id, "pending");
        }
      }
    }
    const styledNodes = nodes.map((node) => {
      const status = stepStatuses.get(node.id) || "pending";
      const timing = stepTimings.get(node.id);
      const duration = timing?.startedAt && timing?.completedAt ? calculateDuration(timing.startedAt, timing.completedAt) : timing?.startedAt ? calculateDuration(timing.startedAt, null) : null;
      let tooltipContent = `${node.data.label || node.id}
`;
      tooltipContent += `Status: ${status}
`;
      if (timing?.startedAt) {
        tooltipContent += `Started: ${timing.startedAt.toLocaleString()}
`;
      }
      if (timing?.completedAt) {
        tooltipContent += `Completed: ${timing.completedAt.toLocaleString()}
`;
      }
      if (duration) {
        tooltipContent += `Duration: ${duration}`;
      }
      let style = {};
      switch (status) {
        case "completed":
          style = {
            backgroundColor: "#10B981",
            // green-500
            color: "white",
            borderColor: "#059669",
            // green-600
            borderWidth: "3px",
            borderRadius: "16px"
          };
          break;
        case "active":
          style = {
            backgroundColor: "#3B82F6",
            // blue-500
            color: "white",
            borderColor: "#1D4ED8",
            // blue-700
            borderWidth: "3px",
            borderRadius: "16px",
            boxShadow: "0 0 0 3px rgba(59, 130, 246, 0.3)"
          };
          break;
        case "failed":
          style = {
            backgroundColor: "#EF4444",
            // red-500
            color: "white",
            borderColor: "#B91C1C",
            // red-700
            borderWidth: "3px",
            borderRadius: "16px"
          };
          break;
        case "skipped":
          style = {
            backgroundColor: "#FEF3C7",
            // yellow-100
            color: "#78350F",
            // yellow-900
            borderColor: "#F59E0B",
            // yellow-500
            borderWidth: "3px",
            borderRadius: "16px"
          };
          break;
        case "pending":
        default:
          style = {
            backgroundColor: "#E5E7EB",
            // gray-200
            color: "#374151",
            // gray-700
            borderColor: "#9CA3AF",
            // gray-400
            borderWidth: "2px",
            borderRadius: "8px"
          };
          break;
      }
      return {
        ...node,
        data: {
          ...node.data,
          status,
          timing,
          duration,
          tooltip: tooltipContent
        },
        style
      };
    });
    return { graphNodes: styledNodes, graphEdges: edges };
  }, [workflowDefinition, events, instance?.currentStepId]);
  if (isLoading) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6" }),
        /* @__PURE__ */ jsx("span", { children: t("workflows.instances.detail.loading") || "Loading workflow instance..." })
      ] }) }),
      ConfirmDialogElement
    ] });
  }
  const isNotFound = !isLoading && error?.status === 404;
  if (isNotFound) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
        RecordNotFoundState,
        {
          label: t("workflows.instances.detail.notFound", "Workflow instance not found."),
          backHref: "/backend/instances",
          backLabel: t("workflows.instances.actions.backToList", "Back to instances")
        }
      ) }),
      ConfirmDialogElement
    ] });
  }
  if (error || !instance) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
        ErrorMessage,
        {
          label: error?.message ?? t("workflows.instances.loadFailed", "Failed to load workflow instance."),
          action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/instances", children: t("workflows.instances.actions.backToList", "Back to instances") }) })
        }
      ) }),
      ConfirmDialogElement
    ] });
  }
  const canCancel = ["RUNNING", "PAUSED"].includes(instance.status);
  const canRetry = instance.status === "FAILED";
  const actionLoading = cancelMutation.isPending || retryMutation.isPending;
  if (isMobile) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsx(
          FormHeader,
          {
            mode: "detail",
            backHref: "/backend/instances",
            backLabel: t("workflows.instances.backToList", "Back to instances"),
            entityTypeLabel: t("workflows.instances.detail.type", "Workflow instance"),
            title: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
              /* @__PURE__ */ jsx("span", { children: instance.workflowId }),
              /* @__PURE__ */ jsxs("span", { className: "font-mono text-sm text-muted-foreground", children: [
                "#",
                instance.id.slice(0, 8)
              ] })
            ] }),
            menuActions: [
              ...canCancel ? [{
                id: "cancel",
                label: t("workflows.instances.actions.cancel"),
                onSelect: handleCancel,
                disabled: actionLoading
              }] : [],
              ...canRetry ? [{
                id: "retry",
                label: t("workflows.instances.actions.retry"),
                onSelect: handleRetry,
                disabled: actionLoading
              }] : []
            ]
          }
        ),
        /* @__PURE__ */ jsx(
          MobileInstanceOverview,
          {
            instance,
            events,
            graphNodes,
            graphEdges,
            definitionLoading,
            hasDefinition: !!workflowDefinition,
            getStatusBadgeClass,
            getEventTypeBadgeClass,
            calculateDuration
          }
        )
      ] }) }),
      ConfirmDialogElement
    ] });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsx(
        FormHeader,
        {
          mode: "detail",
          backHref: "/backend/instances",
          backLabel: t("workflows.instances.backToList", "Back to instances"),
          entityTypeLabel: t("workflows.instances.detail.type", "Workflow instance"),
          title: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
            /* @__PURE__ */ jsx("span", { children: instance.workflowId }),
            /* @__PURE__ */ jsxs("span", { className: "font-mono text-sm text-muted-foreground", children: [
              "#",
              instance.id.slice(0, 8)
            ] })
          ] }),
          menuActions: [
            ...canCancel ? [{
              id: "cancel",
              label: t("workflows.instances.actions.cancel"),
              onSelect: handleCancel,
              disabled: actionLoading
            }] : [],
            ...canRetry ? [{
              id: "retry",
              label: t("workflows.instances.actions.retry"),
              onSelect: handleRetry,
              disabled: actionLoading
            }] : []
          ]
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-4", children: t("workflows.instances.sections.overview") }),
        /* @__PURE__ */ jsxs("dl", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.workflowId") }),
            /* @__PURE__ */ jsxs("dd", { className: "mt-1 text-sm text-foreground", children: [
              /* @__PURE__ */ jsx("div", { className: "font-mono", children: instance.workflowId }),
              /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
                "v",
                instance.version
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.status") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1", children: /* @__PURE__ */ jsx(
              "span",
              {
                className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium ${getStatusBadgeClass(
                  instance.status
                )}`,
                children: t(`workflows.instances.status.${instance.status}`)
              }
            ) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.currentStep") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1 text-sm text-foreground font-mono", children: instance.currentStepId || "-" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.correlationKey") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1 text-sm text-foreground", children: instance.correlationKey || "-" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.startedAt") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1 text-sm text-foreground", children: new Date(instance.startedAt).toLocaleString() })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.completedAt") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1 text-sm text-foreground", children: instance.completedAt ? new Date(instance.completedAt).toLocaleString() : "-" })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.duration") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1 text-sm text-foreground", children: calculateDuration(instance.startedAt, instance.completedAt) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: t("workflows.instances.fields.retryCount") }),
            /* @__PURE__ */ jsx("dd", { className: "mt-1", children: /* @__PURE__ */ jsx("span", { className: instance.retryCount > 0 ? "text-orange-600 font-medium text-sm" : "text-sm text-foreground", children: instance.retryCount }) })
          ] })
        ] })
      ] }),
      definitionLoading && /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-6", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center py-8", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6" }),
        /* @__PURE__ */ jsx("span", { className: "ml-2 text-sm text-muted-foreground", children: "Loading workflow visualization..." })
      ] }) }),
      !definitionLoading && workflowDefinition && graphNodes.length > 0 && /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4 md:p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold text-foreground mb-4", children: t("workflows.instances.sections.visualFlow") || "Visual Workflow Flow" }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 lg:flex-row lg:gap-6", children: [
          /* @__PURE__ */ jsx("div", { className: "order-2 lg:order-1 lg:w-64 lg:flex-shrink-0", children: /* @__PURE__ */ jsx(WorkflowLegend, {}) }),
          /* @__PURE__ */ jsx("div", { className: "order-1 lg:order-2 flex-1 border rounded-lg overflow-hidden h-[62svh] min-h-[360px] lg:h-[800px]", children: /* @__PURE__ */ jsx(
            WorkflowGraphReadOnly,
            {
              nodes: graphNodes,
              edges: graphEdges,
              height: "100%"
            }
          ) })
        ] })
      ] }),
      !definitionLoading && !workflowDefinition && instance && /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-4", children: t("workflows.instances.sections.visualFlow") || "Visual Workflow Flow" }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-8 text-muted-foreground", children: /* @__PURE__ */ jsxs("p", { className: "text-sm", children: [
          "Workflow definition not found (ID: ",
          instance.definitionId,
          ")"
        ] }) })
      ] }),
      (instance.status === "COMPENSATING" || instance.status === "COMPENSATED") && /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-orange-300 bg-orange-50 p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-4 text-orange-800", children: t("workflows.instances.sections.compensation") || "Compensation (Saga Pattern)" }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm text-orange-700", children: instance.status === "COMPENSATING" ? t("workflows.instances.compensation.inProgress") || "Workflow is currently executing compensation activities to rollback changes." : t("workflows.instances.compensation.completed") || "Compensation has been completed. All changes have been rolled back." }),
          events.filter(
            (e) => e.eventType.includes("COMPENSATION") || e.eventType.includes("Compensation")
          ).length > 0 && /* @__PURE__ */ jsxs("div", { className: "mt-4", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium text-orange-800 mb-2", children: t("workflows.instances.compensation.activities") || "Compensation Activities" }),
            /* @__PURE__ */ jsx("div", { className: "space-y-2", children: events.filter((e) => e.eventType.includes("COMPENSATION") || e.eventType.includes("Compensation")).reverse().map((event) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2 p-2 bg-card rounded border border-orange-200", children: [
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${getEventTypeBadgeClass(
                    event.eventType
                  )}`,
                  children: event.eventType
                }
              ),
              /* @__PURE__ */ jsx("span", { className: "text-xs text-orange-600", children: new Date(event.occurredAt).toLocaleTimeString() }),
              event.eventData?.activityName && /* @__PURE__ */ jsx("span", { className: "text-xs text-orange-700 font-medium", children: event.eventData.activityName })
            ] }, event.id)) })
          ] })
        ] })
      ] }),
      instance.errorMessage && /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-destructive bg-destructive/5 p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-4 text-destructive", children: t("workflows.instances.fields.lastError") }),
        /* @__PURE__ */ jsx("pre", { className: "text-sm text-destructive whitespace-pre-wrap font-mono", children: instance.errorMessage }),
        instance.errorDetails && /* @__PURE__ */ jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsx(
          JsonDisplay,
          {
            data: instance.errorDetails,
            className: "border-destructive/20 bg-destructive/5",
            maxInitialDepth: 1
          }
        ) })
      ] }),
      /* @__PURE__ */ jsx(
        JsonDisplay,
        {
          data: instance.context,
          title: t("workflows.instances.sections.context")
        }
      ),
      instance.metadata && Object.keys(instance.metadata).length > 0 && /* @__PURE__ */ jsx(
        JsonDisplay,
        {
          data: instance.metadata,
          title: t("workflows.instances.sections.metadata")
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-4", children: t("workflows.instances.sections.executionTimeline") || "Execution Timeline" }),
        eventsLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground", children: [
          /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm", children: t("common.loading") })
        ] }) : events.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("workflows.instances.noExecutionHistory") }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: events.filter(
          (e) => e.eventType.includes("STEP_") || e.eventType.includes("WORKFLOW_STARTED") || e.eventType.includes("WORKFLOW_COMPLETED") || e.eventType.includes("WORKFLOW_FAILED")
        ).reverse().map((event, idx) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 p-3 bg-muted rounded-lg border", children: [
          /* @__PURE__ */ jsx("div", { className: "flex-shrink-0 w-8 h-8 rounded-full bg-background border-2 border-border flex items-center justify-center text-xs font-medium", children: idx + 1 }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${getEventTypeBadgeClass(
                    event.eventType
                  )}`,
                  children: t(`workflows.events.types.${event.eventType}`) || event.eventType
                }
              ),
              /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: new Date(event.occurredAt).toLocaleTimeString() })
            ] }),
            event.eventData && /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
              event.eventData.toStepId && `-> ${event.eventData.toStepId}`,
              event.eventData.fromStepId && `${event.eventData.fromStepId} -> ${event.eventData.toStepId}`
            ] })
          ] })
        ] }, event.id)) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold mb-4", children: t("workflows.instances.sections.executionHistory") }),
        eventsLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground", children: [
          /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm", children: t("common.loading") })
        ] }) : events.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("workflows.instances.noExecutionHistory") }) : /* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-lg border", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full divide-y divide-border", children: [
          /* @__PURE__ */ jsx("thead", { className: "bg-muted", children: /* @__PURE__ */ jsxs("tr", { children: [
            /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-muted-foreground", children: t("workflows.events.occurredAt") }),
            /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-muted-foreground", children: t("workflows.events.eventType") }),
            /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-muted-foreground", children: t("workflows.events.eventData") }),
            /* @__PURE__ */ jsx("th", { className: "px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-muted-foreground", children: t("workflows.events.userId") })
          ] }) }),
          /* @__PURE__ */ jsx("tbody", { className: "bg-background divide-y divide-border", children: events.map((event) => /* @__PURE__ */ jsxs("tr", { className: "hover:bg-muted/50", children: [
            /* @__PURE__ */ jsx("td", { className: "px-4 py-3 whitespace-nowrap text-sm text-foreground", children: new Date(event.occurredAt).toLocaleString() }),
            /* @__PURE__ */ jsx("td", { className: "px-4 py-3 whitespace-nowrap", children: /* @__PURE__ */ jsx(
              "span",
              {
                className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium ${getEventTypeBadgeClass(
                  event.eventType
                )}`,
                children: t(`workflows.events.types.${event.eventType}`) || event.eventType
              }
            ) }),
            /* @__PURE__ */ jsx("td", { className: "px-4 py-3 text-sm", children: /* @__PURE__ */ jsxs("details", { className: "cursor-pointer", children: [
              /* @__PURE__ */ jsx("summary", { className: "text-primary hover:underline", children: t("common.details") }),
              /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsx(
                JsonDisplay,
                {
                  data: event.eventData,
                  showCopy: false,
                  maxInitialDepth: 1
                }
              ) })
            ] }) }),
            /* @__PURE__ */ jsx("td", { className: "px-4 py-3 whitespace-nowrap text-sm text-muted-foreground", children: event.userId || "-" })
          ] }, event.id)) })
        ] }) })
      ] })
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  WorkflowInstanceDetailPage as default
};
//# sourceMappingURL=page.js.map
