"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useQuery } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
function WorkflowEventsPage() {
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(50);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const t = useT();
  const [filterValues, setFilterValues] = React.useState({});
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["workflows", "events", filterValues, page],
    queryFn: async () => {
      const params = new URLSearchParams();
      params.set("page", page.toString());
      params.set("pageSize", pageSize.toString());
      params.set("sortField", "occurredAt");
      params.set("sortDir", "desc");
      if (filterValues.eventType) params.set("eventType", filterValues.eventType);
      if (filterValues.workflowInstanceId) params.set("workflowInstanceId", filterValues.workflowInstanceId);
      if (filterValues.userId) params.set("userId", filterValues.userId);
      if (filterValues.occurredAtFrom) params.set("occurredAtFrom", filterValues.occurredAtFrom);
      if (filterValues.occurredAtTo) params.set("occurredAtTo", filterValues.occurredAtTo);
      const result = await apiCall(
        `/api/workflows/events?${params.toString()}`
      );
      if (!result.ok) {
        throw new Error("Failed to fetch workflow events");
      }
      const response = result.result;
      if (response) {
        setTotal(response.total || 0);
        setTotalPages(response.totalPages || 1);
      }
      return response?.items || [];
    }
  });
  const handleFiltersApply = React.useCallback((values) => {
    const next = {};
    Object.entries(values).forEach(([key, value]) => {
      if (value !== void 0) next[key] = value;
    });
    setFilterValues(next);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const filters = [
    {
      id: "eventType",
      type: "select",
      label: t("workflows.events.filters.eventType"),
      options: [
        { value: "", label: t("common.all") },
        { value: "WORKFLOW_STARTED", label: t("workflows.events.types.workflow_started") },
        { value: "WORKFLOW_COMPLETED", label: t("workflows.events.types.workflow_completed") },
        { value: "WORKFLOW_FAILED", label: t("workflows.events.types.workflow_failed") },
        { value: "WORKFLOW_CANCELLED", label: t("workflows.events.types.workflow_cancelled") },
        { value: "STEP_ENTERED", label: t("workflows.events.types.step_entered") },
        { value: "STEP_EXITED", label: t("workflows.events.types.step_exited") },
        { value: "TRANSITION_EXECUTED", label: t("workflows.events.types.transition_executed") },
        { value: "TRANSITION_REJECTED", label: t("workflows.events.types.transition_rejected") },
        { value: "ACTIVITY_STARTED", label: t("workflows.events.types.activity_started") },
        { value: "ACTIVITY_COMPLETED", label: t("workflows.events.types.activity_completed") },
        { value: "ACTIVITY_FAILED", label: t("workflows.events.types.activity_failed") }
      ]
    },
    {
      id: "workflowInstanceId",
      type: "text",
      label: t("workflows.events.filters.workflowInstanceId"),
      placeholder: t("workflows.events.filters.workflowInstanceIdPlaceholder")
    },
    {
      id: "userId",
      type: "text",
      label: t("workflows.events.filters.userId"),
      placeholder: t("workflows.events.filters.userIdPlaceholder")
    }
  ];
  const getEventTypeBadgeClass = (eventType) => {
    if (eventType.includes("STARTED")) return "bg-status-info-bg text-status-info-text";
    if (eventType.includes("COMPLETED")) return "bg-status-success-bg text-status-success-text";
    if (eventType.includes("FAILED") || eventType.includes("REJECTED")) return "bg-status-error-bg text-status-error-text";
    if (eventType.includes("CANCELLED")) return "bg-muted text-foreground";
    if (eventType.includes("ENTERED") || eventType.includes("EXITED")) return "bg-status-neutral-bg text-status-neutral-text";
    return "bg-muted text-foreground";
  };
  const columns = [
    {
      id: "occurredAt",
      header: t("workflows.events.fields.occurredAt"),
      accessorKey: "occurredAt",
      cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "text-sm", children: new Date(row.original.occurredAt).toLocaleString() })
    },
    {
      id: "eventType",
      header: t("workflows.events.fields.eventType"),
      accessorKey: "eventType",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        "span",
        {
          className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium ${getEventTypeBadgeClass(
            row.original.eventType
          )}`,
          children: row.original.eventType
        }
      )
    },
    {
      id: "workflow",
      header: t("workflows.events.fields.workflow"),
      cell: ({ row }) => /* @__PURE__ */ jsx("div", { children: row.original.workflowInstance ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          Link,
          {
            href: `/backend/instances/${row.original.workflowInstance.id}`,
            className: "text-primary hover:text-primary/80 hover:underline font-medium",
            children: row.original.workflowInstance.workflowName
          }
        ),
        /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground mt-0.5", children: row.original.workflowInstance.workflowId })
      ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: t("workflows.events.workflowNotFound") }) })
    },
    {
      id: "instance",
      header: t("workflows.events.fields.instance"),
      cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "text-sm", children: /* @__PURE__ */ jsxs(
        Link,
        {
          href: `/backend/instances/${row.original.workflowInstanceId}`,
          className: "text-primary hover:text-primary/80 hover:underline font-mono text-xs",
          children: [
            row.original.workflowInstanceId.substring(0, 8),
            "..."
          ]
        }
      ) })
    },
    {
      id: "status",
      header: t("workflows.events.fields.status"),
      cell: ({ row }) => /* @__PURE__ */ jsx("div", { children: row.original.workflowInstance && /* @__PURE__ */ jsx(
        "span",
        {
          className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium ${row.original.workflowInstance.status === "COMPLETED" ? "bg-status-success-bg text-status-success-text" : row.original.workflowInstance.status === "RUNNING" ? "bg-status-info-bg text-status-info-text" : row.original.workflowInstance.status === "FAILED" ? "bg-status-error-bg text-status-error-text" : "bg-muted text-foreground"}`,
          children: row.original.workflowInstance.status
        }
      ) })
    },
    {
      id: "userId",
      header: t("workflows.events.fields.userId"),
      accessorKey: "userId",
      cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground font-mono text-xs", children: row.original.userId ? row.original.userId.substring(0, 8) + "..." : "-" })
    },
    {
      id: "eventData",
      header: t("workflows.events.fields.eventData"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground max-w-xs truncate", children: [
        JSON.stringify(row.original.eventData).substring(0, 50),
        "..."
      ] })
    },
    {
      id: "actions",
      header: "",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        Link,
        {
          href: `/backend/events/${row.original.id}`,
          className: "text-sm text-primary hover:text-primary/80 hover:underline",
          children: t("common.details")
        }
      )
    }
  ];
  if (error) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: t("workflows.events.messages.loadFailed"),
        description: error.message,
        action: /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => refetch(), children: t("common.retry", "Retry") })
      }
    ) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    DataTable,
    {
      title: t("workflows.events.list.title"),
      columns,
      data: data || [],
      filters,
      filterValues,
      onFiltersApply: handleFiltersApply,
      onFiltersClear: handleFiltersClear,
      isLoading,
      pagination: { page, pageSize, total, totalPages, onPageChange: setPage },
      actions: /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: () => refetch(),
          disabled: isLoading,
          children: isLoading ? t("common.refreshing") : t("common.refresh")
        }
      )
    }
  ) }) });
}
export {
  WorkflowEventsPage as default
};
//# sourceMappingURL=page.js.map
