"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useState } from "react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { JsonDisplay } from "@open-mercato/ui/backend/JsonDisplay";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { WorkflowGraphReadOnly } from "../WorkflowGraph.js";
import { MobileWorkflowTimeline } from "./MobileWorkflowTimeline.js";
import { ChevronDown, ChevronUp, Maximize2 } from "lucide-react";
function MobileInstanceOverview({
  instance,
  events,
  graphNodes,
  graphEdges,
  definitionLoading,
  hasDefinition,
  getStatusBadgeClass,
  getEventTypeBadgeClass,
  calculateDuration
}) {
  const t = useT();
  const [showFullGraph, setShowFullGraph] = useState(false);
  const [expandedEvents, setExpandedEvents] = useState(/* @__PURE__ */ new Set());
  const toggleEventDetails = (eventId) => {
    setExpandedEvents((prev) => {
      const next = new Set(prev);
      if (next.has(eventId)) {
        next.delete(eventId);
      } else {
        next.add(eventId);
      }
      return next;
    });
  };
  const timelineSteps = React.useMemo(() => {
    return graphNodes.map((node) => ({
      id: node.id,
      label: node.data?.label || node.id,
      type: node.type || "unknown",
      status: node.data?.status || "pending",
      duration: node.data?.duration || null
    }));
  }, [graphNodes]);
  const timelineEvents = React.useMemo(() => {
    return events.filter(
      (e) => e.eventType.includes("STEP_") || e.eventType.includes("WORKFLOW_STARTED") || e.eventType.includes("WORKFLOW_COMPLETED") || e.eventType.includes("WORKFLOW_FAILED")
    ).reverse();
  }, [events]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "mb-3 text-base font-semibold", children: t("workflows.instances.sections.overview") }),
      /* @__PURE__ */ jsxs("dl", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.status") }),
          /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded px-2 py-0.5 text-xs font-medium ${getStatusBadgeClass(instance.status)}`, children: t(`workflows.instances.status.${instance.status}`) }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.workflowId") }),
          /* @__PURE__ */ jsxs("dd", { className: "text-right", children: [
            /* @__PURE__ */ jsx("div", { className: "text-sm font-mono", children: instance.workflowId }),
            /* @__PURE__ */ jsxs("div", { className: "text-overline text-muted-foreground", children: [
              "v",
              instance.version
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.currentStep") }),
          /* @__PURE__ */ jsx("dd", { className: "text-sm font-mono text-right", children: instance.currentStepId || "-" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.duration") }),
          /* @__PURE__ */ jsx("dd", { className: "text-sm", children: calculateDuration(instance.startedAt, instance.completedAt) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.startedAt") }),
          /* @__PURE__ */ jsx("dd", { className: "text-xs", children: new Date(instance.startedAt).toLocaleString() })
        ] }),
        instance.completedAt && /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.completedAt") }),
          /* @__PURE__ */ jsx("dd", { className: "text-xs", children: new Date(instance.completedAt).toLocaleString() })
        ] }),
        instance.retryCount > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: t("workflows.instances.fields.retryCount") }),
          /* @__PURE__ */ jsx("dd", { className: "text-sm font-medium text-orange-600", children: instance.retryCount })
        ] })
      ] })
    ] }),
    definitionLoading && /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center py-6", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-5 w-5" }),
      /* @__PURE__ */ jsx("span", { className: "ml-2 text-sm text-muted-foreground", children: t("common.loading") })
    ] }) }),
    !definitionLoading && hasDefinition && timelineSteps.length > 0 && /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center justify-between", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-base font-semibold", children: t("workflows.mobile.stepTimeline", "Step Timeline") }),
        /* @__PURE__ */ jsxs(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: () => setShowFullGraph(true),
            className: "h-7 text-xs",
            children: [
              /* @__PURE__ */ jsx(Maximize2, { className: "mr-1 h-3 w-3" }),
              t("workflows.mobile.viewFullGraph", "View Full Graph")
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsx(MobileWorkflowTimeline, { steps: timelineSteps })
    ] }),
    instance.errorMessage && /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-destructive bg-destructive/5 p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "mb-2 text-sm font-semibold text-destructive", children: t("workflows.instances.fields.lastError") }),
      /* @__PURE__ */ jsx("pre", { className: "text-xs text-destructive whitespace-pre-wrap font-mono break-all", children: instance.errorMessage })
    ] }),
    /* @__PURE__ */ jsx(
      JsonDisplay,
      {
        data: instance.context,
        title: t("workflows.instances.sections.context")
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "mb-3 text-base font-semibold", children: t("workflows.instances.sections.executionTimeline") }),
      timelineEvents.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("workflows.instances.noExecutionHistory") }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: timelineEvents.map((event, idx) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2 rounded-lg border bg-muted p-2.5", children: [
        /* @__PURE__ */ jsx("div", { className: "flex h-6 w-6 shrink-0 items-center justify-center rounded-full border bg-background text-overline font-medium", children: idx + 1 }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [
            /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded px-1.5 py-0.5 text-overline font-medium ${getEventTypeBadgeClass(event.eventType)}`, children: t(`workflows.events.types.${event.eventType}`) || event.eventType }),
            /* @__PURE__ */ jsx("span", { className: "text-overline text-muted-foreground", children: new Date(event.occurredAt).toLocaleTimeString() })
          ] }),
          event.eventData?.toStepId && /* @__PURE__ */ jsxs("p", { className: "mt-0.5 text-overline text-muted-foreground", children: [
            event.eventData.fromStepId ? `${event.eventData.fromStepId} -> ` : "-> ",
            event.eventData.toStepId
          ] })
        ] })
      ] }, event.id)) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "mb-3 text-base font-semibold", children: t("workflows.mobile.eventLog", "Event Log") }),
      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.map((event) => {
        const isExpanded = expandedEvents.has(event.id);
        return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-background p-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
              /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-1.5", children: /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded px-1.5 py-0.5 text-overline font-medium ${getEventTypeBadgeClass(event.eventType)}`, children: t(`workflows.events.types.${event.eventType}`) || event.eventType }) }),
              /* @__PURE__ */ jsx("div", { className: "mt-1 text-overline text-muted-foreground", children: new Date(event.occurredAt).toLocaleString() })
            ] }),
            event.eventData && /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => toggleEventDetails(event.id),
                className: "shrink-0 rounded p-1 hover:bg-muted",
                "aria-label": isExpanded ? t("workflows.mobile.hideDetails") : t("workflows.mobile.showDetails"),
                children: isExpanded ? /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
              }
            )
          ] }),
          isExpanded && event.eventData && /* @__PURE__ */ jsx("div", { className: "mt-2 border-t pt-2", children: /* @__PURE__ */ jsx(
            JsonDisplay,
            {
              data: event.eventData,
              showCopy: false,
              maxInitialDepth: 1
            }
          ) })
        ] }, event.id);
      }) })
    ] }),
    /* @__PURE__ */ jsx(Dialog, { open: showFullGraph, onOpenChange: setShowFullGraph, children: /* @__PURE__ */ jsxs(DialogContent, { className: "h-[90svh] max-w-[95vw] p-0", children: [
      /* @__PURE__ */ jsx(DialogHeader, { className: "px-4 pt-4", children: /* @__PURE__ */ jsx(DialogTitle, { children: t("workflows.instances.sections.visualFlow") }) }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 p-2", children: /* @__PURE__ */ jsx(
        WorkflowGraphReadOnly,
        {
          nodes: graphNodes,
          edges: graphEdges,
          height: "calc(90svh - 80px)"
        }
      ) })
    ] }) })
  ] });
}
export {
  MobileInstanceOverview
};
//# sourceMappingURL=MobileInstanceOverview.js.map
