"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { BarChart2, ChevronRight, Loader2 } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
function todayIso() {
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
}
function daysAgoIso(days) {
  const date = /* @__PURE__ */ new Date();
  date.setDate(date.getDate() - days);
  return date.toISOString().slice(0, 10);
}
async function fetchDailyRollup(from, to) {
  const params = new URLSearchParams({ from, to });
  const { result, status } = await apiCallOrThrow(
    `/api/ai_assistant/usage/daily?${params}`,
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load daily token usage" }
  );
  if (!result) throw new Error(`Failed to load daily usage (${status})`);
  return result;
}
async function fetchSessions(from, to, offset) {
  const params = new URLSearchParams({ from, to, limit: "50", offset: String(offset) });
  const { result, status } = await apiCallOrThrow(
    `/api/ai_assistant/usage/sessions?${params}`,
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load session list" }
  );
  if (!result) throw new Error(`Failed to load sessions (${status})`);
  return result;
}
async function fetchSessionDetail(sessionId) {
  const { result, status } = await apiCallOrThrow(
    `/api/ai_assistant/usage/sessions/${encodeURIComponent(sessionId)}`,
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load session detail" }
  );
  if (!result) throw new Error(`Failed to load session detail (${status})`);
  return result;
}
function sumBigintRows(rows, field) {
  return rows.reduce((acc, row) => acc + parseInt(String(row[field] ?? "0"), 10), 0);
}
function formatNumber(value) {
  return value.toLocaleString();
}
function formatDate(iso) {
  return new Date(iso).toLocaleString();
}
function shortId(id) {
  return id.slice(0, 8);
}
function AiUsageStatsPageClient() {
  const t = useT();
  const defaultFrom = daysAgoIso(30);
  const defaultTo = todayIso();
  const [from, setFrom] = React.useState(defaultFrom);
  const [to, setTo] = React.useState(defaultTo);
  const [appliedFrom, setAppliedFrom] = React.useState(defaultFrom);
  const [appliedTo, setAppliedTo] = React.useState(defaultTo);
  const [sessionsOffset, setSessionsOffset] = React.useState(0);
  const [selectedSessionId, setSelectedSessionId] = React.useState(null);
  const dailyQuery = useQuery({
    queryKey: ["ai-usage-daily", appliedFrom, appliedTo],
    queryFn: () => fetchDailyRollup(appliedFrom, appliedTo)
  });
  const sessionsQuery = useQuery({
    queryKey: ["ai-usage-sessions", appliedFrom, appliedTo, sessionsOffset],
    queryFn: () => fetchSessions(appliedFrom, appliedTo, sessionsOffset)
  });
  const sessionDetailQuery = useQuery({
    queryKey: ["ai-usage-session-detail", selectedSessionId],
    queryFn: () => fetchSessionDetail(selectedSessionId),
    enabled: selectedSessionId !== null
  });
  function applyFilter() {
    setSessionsOffset(0);
    setAppliedFrom(from);
    setAppliedTo(to);
  }
  const dailyRows = dailyQuery.data?.rows ?? [];
  const totalInputTokens = sumBigintRows(dailyRows, "inputTokens");
  const totalOutputTokens = sumBigintRows(dailyRows, "outputTokens");
  const totalSteps = sumBigintRows(dailyRows, "stepCount");
  const totalSessions = sumBigintRows(dailyRows, "sessionCount");
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6 max-w-5xl", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsx(BarChart2, { className: "text-muted-foreground", size: 20 }),
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("ai_assistant.usage.title", "Token Usage Statistics") })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-4 flex-wrap", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "usage-from", children: t("ai_assistant.usage.from", "From") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "usage-from",
            type: "date",
            value: from,
            onChange: (e) => setFrom(e.target.value),
            className: "w-40"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "usage-to", children: t("ai_assistant.usage.to", "To") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "usage-to",
            type: "date",
            value: to,
            onChange: (e) => setTo(e.target.value),
            className: "w-40"
          }
        )
      ] }),
      /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: applyFilter, children: t("ai_assistant.usage.apply", "Apply") })
    ] }),
    dailyQuery.isLoading && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground text-sm", children: [
      /* @__PURE__ */ jsx(Loader2, { size: 14, className: "animate-spin" }),
      t("ai_assistant.usage.loading", "Loading usage data...")
    ] }),
    dailyQuery.isError && /* @__PURE__ */ jsx("p", { className: "text-status-error-text text-sm", children: t("ai_assistant.usage.error", "Failed to load usage data.") }),
    dailyQuery.isSuccess && /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-4", children: [
      { label: t("ai_assistant.usage.inputTokens", "Input tokens"), value: formatNumber(totalInputTokens) },
      { label: t("ai_assistant.usage.outputTokens", "Output tokens"), value: formatNumber(totalOutputTokens) },
      { label: t("ai_assistant.usage.steps", "Steps"), value: formatNumber(totalSteps) },
      { label: t("ai_assistant.usage.sessions", "Sessions"), value: formatNumber(totalSessions) }
    ].map((tile) => /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border p-4 space-y-1", children: [
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: tile.label }),
      /* @__PURE__ */ jsx("p", { className: "font-semibold text-xl", children: tile.value })
    ] }, tile.label)) }),
    dailyQuery.isSuccess && dailyRows.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium text-muted-foreground", children: t("ai_assistant.usage.dailyBreakdown", "Daily breakdown") }),
      /* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-lg border border-border", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full text-sm", children: [
        /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-border bg-muted/40", children: [
          /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.day", "Day") }),
          /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.agent", "Agent") }),
          /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.inputTokens", "Input") }),
          /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.outputTokens", "Output") }),
          /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.sessions", "Sessions") })
        ] }) }),
        /* @__PURE__ */ jsx("tbody", { children: dailyRows.map((row) => /* @__PURE__ */ jsxs("tr", { className: "border-b border-border last:border-b-0", children: [
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 tabular-nums", children: row.day }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 font-mono text-xs", children: row.agentId }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: formatNumber(parseInt(row.inputTokens, 10)) }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: formatNumber(parseInt(row.outputTokens, 10)) }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: row.sessionCount })
        ] }, row.id)) })
      ] }) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium text-muted-foreground", children: t("ai_assistant.usage.sessionsList", "Sessions") }),
      sessionsQuery.isLoading && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground text-sm", children: [
        /* @__PURE__ */ jsx(Loader2, { size: 14, className: "animate-spin" }),
        t("ai_assistant.usage.loadingSessions", "Loading sessions...")
      ] }),
      sessionsQuery.isError && /* @__PURE__ */ jsx("p", { className: "text-status-error-text text-sm", children: t("ai_assistant.usage.errorSessions", "Failed to load sessions.") }),
      sessionsQuery.isSuccess && (sessionsQuery.data?.sessions ?? []).length === 0 && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: t("ai_assistant.usage.noSessions", "No sessions found for the selected period.") }),
      sessionsQuery.isSuccess && (sessionsQuery.data?.sessions ?? []).length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-lg border border-border", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full text-sm", children: [
          /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-border bg-muted/40", children: [
            /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.session", "Session") }),
            /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.agent", "Agent") }),
            /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.startedAt", "Started") }),
            /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.inputTokens", "Input") }),
            /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.outputTokens", "Output") }),
            /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.steps", "Steps") }),
            /* @__PURE__ */ jsx("th", { className: "w-8" })
          ] }) }),
          /* @__PURE__ */ jsx("tbody", { children: (sessionsQuery.data?.sessions ?? []).map((session) => /* @__PURE__ */ jsxs(
            "tr",
            {
              className: "border-b border-border last:border-b-0 cursor-pointer hover:bg-muted/30 transition-colors",
              onClick: () => setSelectedSessionId(session.sessionId),
              children: [
                /* @__PURE__ */ jsxs("td", { className: "px-3 py-2 font-mono text-xs", children: [
                  shortId(session.sessionId),
                  "\u2026"
                ] }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 font-mono text-xs", children: session.agentId }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground text-xs", children: formatDate(session.startedAt) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: formatNumber(session.inputTokens) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: formatNumber(session.outputTokens) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: session.stepCount }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground", children: /* @__PURE__ */ jsx(ChevronRight, { size: 14 }) })
              ]
            },
            session.sessionId
          )) })
        ] }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: "secondary",
              size: "sm",
              disabled: sessionsOffset === 0,
              onClick: () => setSessionsOffset(Math.max(0, sessionsOffset - 50)),
              children: t("ai_assistant.usage.prev", "Previous")
            }
          ),
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground text-sm", children: [
            sessionsOffset + 1,
            "\u2013",
            sessionsOffset + (sessionsQuery.data?.sessions.length ?? 0),
            sessionsQuery.data?.total !== void 0 ? ` / ${sessionsQuery.data.total}` : ""
          ] }),
          /* @__PURE__ */ jsx(
            Button,
            {
              variant: "secondary",
              size: "sm",
              disabled: (sessionsQuery.data?.sessions.length ?? 0) < 50 || sessionsOffset + 50 >= (sessionsQuery.data?.total ?? 0),
              onClick: () => setSessionsOffset(sessionsOffset + 50),
              children: t("ai_assistant.usage.next", "Next")
            }
          )
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      Dialog,
      {
        open: selectedSessionId !== null,
        onOpenChange: (open) => {
          if (!open) setSelectedSessionId(null);
        },
        children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-3xl max-h-[80vh] overflow-y-auto", children: [
          /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsxs(DialogTitle, { children: [
            t("ai_assistant.usage.sessionDetail", "Session detail"),
            selectedSessionId && /* @__PURE__ */ jsxs("span", { className: "ml-2 font-mono text-sm text-muted-foreground", children: [
              shortId(selectedSessionId),
              "\u2026"
            ] })
          ] }) }),
          /* @__PURE__ */ jsxs("div", { className: "mt-4", children: [
            sessionDetailQuery.isLoading && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground text-sm", children: [
              /* @__PURE__ */ jsx(Loader2, { size: 14, className: "animate-spin" }),
              t("ai_assistant.usage.loadingDetail", "Loading session events...")
            ] }),
            sessionDetailQuery.isError && /* @__PURE__ */ jsx("p", { className: "text-status-error-text text-sm", children: t("ai_assistant.usage.errorDetail", "Failed to load session events.") }),
            sessionDetailQuery.isSuccess && /* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-lg border border-border", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full text-sm", children: [
              /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b border-border bg-muted/40", children: [
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.step", "Step") }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.model", "Model") }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.inputTokens", "Input") }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium text-muted-foreground", children: t("ai_assistant.usage.col.outputTokens", "Output") }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left font-medium text-muted-foreground", children: t("ai_assistant.usage.col.finishReason", "Finish") })
              ] }) }),
              /* @__PURE__ */ jsx("tbody", { children: (sessionDetailQuery.data?.events ?? []).map((event) => /* @__PURE__ */ jsxs("tr", { className: "border-b border-border last:border-b-0", children: [
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 tabular-nums", children: event.stepIndex }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 font-mono text-xs", children: event.modelId }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: formatNumber(event.inputTokens) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums", children: formatNumber(event.outputTokens) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground text-xs", children: event.finishReason ?? "\u2014" })
              ] }, event.id)) })
            ] }) })
          ] })
        ] })
      }
    )
  ] });
}
export {
  AiUsageStatsPageClient
};
//# sourceMappingURL=AiUsageStatsPageClient.js.map
