"use client";
import { 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 { Button } from "@open-mercato/ui/primitives/button";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { ArrowLeft, RefreshCw } from "lucide-react";
const STATUS_COLORS = {
  received: "bg-blue-100 text-blue-800",
  processing: "bg-purple-100 text-purple-800",
  processed: "bg-green-100 text-green-800",
  needs_review: "bg-amber-100 text-amber-800",
  failed: "bg-red-100 text-red-800"
};
function ProcessingLogPage() {
  const t = useT();
  const [items, setItems] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(25);
  const [statusFilter, setStatusFilter] = React.useState();
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [retryingEmailId, setRetryingEmailId] = React.useState(null);
  const { runMutation } = useGuardedMutation({
    contextId: "inbox-ops-log"
  });
  const loadEmails = React.useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", String(pageSize));
    if (statusFilter) params.set("status", statusFilter);
    try {
      const result = await apiCall(`/api/inbox_ops/emails?${params}`);
      if (result?.ok && result.result?.items) {
        setItems(result.result.items);
        setTotal(result.result.total || 0);
      } else {
        setError(t("inbox_ops.log.load_failed", "Failed to load processing log"));
      }
    } catch {
      setError(t("inbox_ops.log.load_failed", "Failed to load processing log"));
    }
    setIsLoading(false);
  }, [page, pageSize, statusFilter, t]);
  React.useEffect(() => {
    loadEmails();
  }, [loadEmails]);
  const handleRetryEmail = React.useCallback(async (emailId) => {
    setRetryingEmailId(emailId);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/emails/${emailId}/reprocess`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.flash.reprocessing_started", "Reprocessing started"), "success");
      await loadEmails();
    } else {
      flash(result?.result?.error || t("inbox_ops.extraction_failed", "Extraction failed"), "error");
    }
    setRetryingEmailId(null);
  }, [loadEmails, t, runMutation]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "subject",
      header: t("inbox_ops.log.subject", "Subject"),
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm font-medium truncate max-w-[300px] block", children: row.original.subject })
    },
    {
      accessorKey: "forwardedByAddress",
      header: t("inbox_ops.log.from", "From"),
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground truncate max-w-[200px] block", children: row.original.forwardedByName || row.original.forwardedByAddress })
    },
    {
      accessorKey: "status",
      header: t("inbox_ops.log.status", "Status"),
      cell: ({ row }) => {
        const statusLabels = {
          received: t("inbox_ops.log.tab_received", "Received"),
          processing: t("inbox_ops.log.tab_processing", "Processing"),
          processed: t("inbox_ops.log.tab_processed", "Processed"),
          needs_review: t("inbox_ops.log.tab_needs_review", "Needs Review"),
          failed: t("inbox_ops.log.tab_failed", "Failed")
        };
        const color = STATUS_COLORS[row.original.status] || "bg-gray-100 text-gray-800";
        const label = statusLabels[row.original.status] || row.original.status;
        return /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${color}`, children: label });
      }
    },
    {
      accessorKey: "receivedAt",
      header: t("inbox_ops.received_at", "Received"),
      cell: ({ row }) => {
        const d = new Date(row.original.receivedAt);
        return /* @__PURE__ */ jsxs("span", { className: "text-sm text-muted-foreground", children: [
          d.toLocaleDateString(),
          " ",
          d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
        ] });
      }
    },
    {
      accessorKey: "processingError",
      header: t("inbox_ops.extraction_failed", "Error"),
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-red-600 truncate max-w-[280px] block", children: row.original.processingError || "-" })
    },
    {
      id: "actions",
      header: t("ui.actions.actions", "Actions"),
      cell: ({ row }) => {
        const canRetry = row.original.status === "failed" || row.original.status === "needs_review";
        if (!canRetry) {
          return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "-" });
        }
        const isRetrying = retryingEmailId === row.original.id;
        return /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            className: "h-8",
            disabled: isRetrying,
            onClick: () => handleRetryEmail(row.original.id),
            children: [
              /* @__PURE__ */ jsx(RefreshCw, { className: `h-3.5 w-3.5 mr-1 ${isRetrying ? "animate-spin" : ""}` }),
              t("inbox_ops.action.retry", "Retry")
            ]
          }
        );
      }
    }
  ], [handleRetryEmail, retryingEmailId, t]);
  const tabs = [
    { label: t("inbox_ops.log.tab_all", "All"), value: void 0 },
    { label: t("inbox_ops.log.tab_received", "Received"), value: "received" },
    { label: t("inbox_ops.log.tab_processing", "Processing"), value: "processing" },
    { label: t("inbox_ops.log.tab_processed", "Processed"), value: "processed" },
    { label: t("inbox_ops.log.tab_needs_review", "Needs Review"), value: "needs_review" },
    { label: t("inbox_ops.log.tab_failed", "Failed"), value: "failed" }
  ];
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-3 py-3 md:px-6 md:py-4", children: [
      /* @__PURE__ */ jsx(Link, { href: "/backend/inbox-ops", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "sm", children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4" }) }) }),
      /* @__PURE__ */ jsx("h1", { className: "text-lg font-semibold", children: t("inbox_ops.processing_log", "Processing Log") })
    ] }),
    /* @__PURE__ */ jsxs(PageBody, { children: [
      /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 px-3 py-2 md:px-0 overflow-x-auto", children: tabs.map((tab) => /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: statusFilter === tab.value ? "default" : "outline",
          size: "sm",
          onClick: () => {
            setStatusFilter(tab.value);
            setPage(1);
          },
          children: tab.label
        },
        tab.value ?? "all"
      )) }),
      error ? /* @__PURE__ */ jsx(ErrorMessage, { label: error }) : /* @__PURE__ */ jsx("div", { className: "overflow-auto", children: /* @__PURE__ */ jsx("div", { className: "min-w-[640px]", children: /* @__PURE__ */ jsx(
        DataTable,
        {
          columns,
          data: items,
          isLoading,
          pagination: {
            page,
            pageSize,
            total,
            totalPages: Math.ceil(total / pageSize),
            onPageChange: setPage
          }
        }
      ) }) })
    ] })
  ] });
}
export {
  ProcessingLogPage as default
};
//# sourceMappingURL=page.js.map
