"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { Button } from "@open-mercato/ui/primitives/button";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
function WorkflowInstancesListPage() {
  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 router = useRouter();
  const queryClient = useQueryClient();
  const { confirm: confirmDialog, ConfirmDialogElement } = useConfirmDialog();
  const [filterValues, setFilterValues] = React.useState({});
  const { data, isLoading, error } = useQuery({
    queryKey: ["workflow-instances", "list", filterValues, page],
    queryFn: async () => {
      const params = new URLSearchParams();
      const offset = (page - 1) * pageSize;
      params.set("limit", pageSize.toString());
      params.set("offset", offset.toString());
      if (filterValues.status) params.set("status", filterValues.status);
      if (filterValues.workflowId) params.set("workflowId", filterValues.workflowId);
      if (filterValues.correlationKey) params.set("correlationKey", filterValues.correlationKey);
      if (filterValues.entityType) params.set("entityType", filterValues.entityType);
      if (filterValues.entityId) params.set("entityId", filterValues.entityId);
      const result = await apiCall(
        `/api/workflows/instances?${params.toString()}`
      );
      if (!result.ok) {
        throw new Error("Failed to fetch workflow instances");
      }
      const response = result.result;
      if (response?.pagination) {
        setTotal(response.pagination.total || 0);
        const calculatedPages = Math.ceil((response.pagination.total || 0) / pageSize);
        setTotalPages(calculatedPages || 1);
      }
      return response?.data || [];
    }
  });
  const handleCancel = async (id, workflowId) => {
    const confirmed = await confirmDialog({
      title: t("workflows.instances.confirm.cancel", { id: workflowId }),
      variant: "destructive"
    });
    if (!confirmed) {
      return;
    }
    const result = await apiCall(`/api/workflows/instances/${id}/cancel`, {
      method: "POST"
    });
    if (result.ok) {
      flash(t("workflows.instances.messages.cancelled"), "success");
      queryClient.invalidateQueries({ queryKey: ["workflow-instances"] });
    } else {
      flash(t("workflows.instances.messages.cancelFailed"), "error");
    }
  };
  const handleRetry = async (id, workflowId) => {
    const ok = await confirmDialog({
      title: t("workflows.instances.confirm.retry", { id: workflowId }),
      variant: "default"
    });
    if (!ok) {
      return;
    }
    const result = await apiCall(`/api/workflows/instances/${id}/retry`, {
      method: "POST"
    });
    if (result.ok) {
      flash(t("workflows.instances.messages.retried"), "success");
      queryClient.invalidateQueries({ queryKey: ["workflow-instances"] });
    } else {
      flash(t("workflows.instances.messages.retryFailed"), "error");
    }
  };
  const handleFiltersApply = React.useCallback((values) => {
    const next = {};
    Object.entries(values).forEach(([key, value]) => {
      if (value !== void 0 && value !== "") next[key] = value;
    });
    setFilterValues(next);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const getStatusBadgeClass = (status) => {
    switch (status) {
      case "RUNNING":
        return "bg-blue-100 text-blue-800";
      case "PAUSED":
        return "bg-yellow-100 text-yellow-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 filters = [
    {
      id: "status",
      type: "select",
      label: t("workflows.instances.filters.status"),
      options: [
        { label: t("common.all"), value: "" },
        { label: t("workflows.instances.status.RUNNING"), value: "RUNNING" },
        { label: t("workflows.instances.status.PAUSED"), value: "PAUSED" },
        { label: t("workflows.instances.status.COMPLETED"), value: "COMPLETED" },
        { label: t("workflows.instances.status.FAILED"), value: "FAILED" },
        { label: t("workflows.instances.status.CANCELLED"), value: "CANCELLED" },
        { label: t("workflows.instances.status.COMPENSATING"), value: "COMPENSATING" },
        { label: t("workflows.instances.status.COMPENSATED"), value: "COMPENSATED" }
      ]
    },
    {
      id: "workflowId",
      type: "text",
      label: t("workflows.instances.filters.workflowId"),
      placeholder: t("workflows.instances.filters.workflowIdPlaceholder")
    },
    {
      id: "correlationKey",
      type: "text",
      label: t("workflows.instances.filters.correlationKey"),
      placeholder: t("workflows.instances.filters.correlationKeyPlaceholder")
    },
    {
      id: "entityType",
      type: "text",
      label: t("workflows.instances.filters.entityType"),
      placeholder: t("workflows.instances.filters.entityTypePlaceholder")
    },
    {
      id: "entityId",
      type: "text",
      label: t("workflows.instances.filters.entityId"),
      placeholder: t("workflows.instances.filters.entityIdPlaceholder")
    }
  ];
  const columns = [
    {
      id: "workflowId",
      header: t("workflows.instances.fields.workflowId"),
      accessorKey: "workflowId",
      cell: ({ row }) => /* @__PURE__ */ jsxs(Link, { href: `/backend/instances/${row.original.id}`, className: "block hover:underline", children: [
        /* @__PURE__ */ jsx("div", { className: "font-mono text-sm font-medium", children: row.original.workflowId }),
        row.original.correlationKey && /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
          t("workflows.instances.fields.correlationKey"),
          ": ",
          row.original.correlationKey
        ] })
      ] })
    },
    {
      id: "status",
      header: t("workflows.instances.fields.status"),
      accessorKey: "status",
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium ${getStatusBadgeClass(row.original.status)}`, children: t(`workflows.instances.status.${row.original.status}`) })
    },
    {
      id: "currentStep",
      header: t("workflows.instances.fields.currentStep"),
      accessorKey: "currentStepId",
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: row.original.currentStepId })
    },
    {
      id: "timing",
      header: t("workflows.instances.fields.timing"),
      cell: ({ row }) => {
        const started = new Date(row.original.startedAt);
        const completed = row.original.completedAt ? new Date(row.original.completedAt) : null;
        const duration = completed ? completed.getTime() - started.getTime() : Date.now() - started.getTime();
        const durationText = duration < 6e4 ? `${Math.floor(duration / 1e3)}s` : `${Math.floor(duration / 6e4)}m`;
        return /* @__PURE__ */ jsxs("div", { className: "text-sm", children: [
          /* @__PURE__ */ jsx("div", { className: "text-foreground", children: started.toLocaleString() }),
          /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
            completed ? t("workflows.instances.duration") : t("workflows.instances.elapsed"),
            ": ",
            durationText
          ] })
        ] });
      }
    },
    {
      id: "retryCount",
      header: t("workflows.instances.fields.retryCount"),
      accessorKey: "retryCount",
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: `text-sm ${row.original.retryCount > 0 ? "text-orange-600 font-medium" : "text-muted-foreground"}`, children: row.original.retryCount })
    },
    {
      id: "actions",
      header: "",
      cell: ({ row }) => {
        const items = [
          {
            id: "view",
            label: t("workflows.instances.actions.viewDetails"),
            href: `/backend/instances/${row.original.id}`
          }
        ];
        if (row.original.status === "RUNNING" || row.original.status === "PAUSED") {
          items.push({
            id: "cancel",
            label: t("workflows.instances.actions.cancel"),
            onSelect: () => void handleCancel(row.original.id, row.original.workflowId)
          });
        }
        if (row.original.status === "FAILED") {
          items.push({
            id: "retry",
            label: t("workflows.instances.actions.retry"),
            onSelect: () => void handleRetry(row.original.id, row.original.workflowId)
          });
        }
        return /* @__PURE__ */ jsx(RowActions, { items });
      }
    }
  ];
  if (error) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "p-8 text-center", children: [
      /* @__PURE__ */ jsx("p", { className: "text-red-600", children: t("workflows.instances.messages.loadFailed") }),
      /* @__PURE__ */ jsx(Button, { onClick: () => queryClient.invalidateQueries({ queryKey: ["workflow-instances"] }), className: "mt-4", children: t("common.retry") })
    ] }) }) });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("workflows.instances.list.title"),
        columns,
        data: data || [],
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        perspective: {
          tableId: "workflows.instances.list"
        },
        pagination: { page, pageSize, total, totalPages, onPageChange: setPage }
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  WorkflowInstancesListPage as default
};
//# sourceMappingURL=page.js.map
