%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/pages/
Upload File :
Create Path :
Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/pages/UsagePage.tsx

import { useState } from "react";
import {
  Area,
  AreaChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import Card, { CardBody, CardHeader } from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import Button from "@/components/ui/Button";
import { useUsage } from "@/hooks/useUsage";
import { useUsageRequests } from "@/hooks/useUsageRequests";
import {
  formatCompact,
  formatDateTime,
  formatIDR,
  formatNumber,
} from "@/lib/format";
import type { DailyUsageRow, UsageRequestRow } from "@/types/api";

const PERIODS = [
  { value: 1, label: "Hari ini" },
  { value: 7, label: "7 hari" },
  { value: 30, label: "30 hari" },
  { value: 90, label: "90 hari" },
  { value: 0, label: "Semua" },
];

type TrendMetric = "requests" | "tokens";
type LogFilter = "all" | "wallet" | "package";

const TREND: Record<
  TrendMetric,
  { label: string; key: "requests" | "total_tokens"; color: string }
> = {
  requests: { label: "Requests", key: "requests", color: "#3b82f6" },
  tokens: { label: "Token", key: "total_tokens", color: "#93c5fd" },
};

const LOG_FILTERS: { value: LogFilter; label: string }[] = [
  { value: "all", label: "Semua" },
  { value: "wallet", label: "Dipotong Wallet" },
  { value: "package", label: "Ditanggung Paket" },
];

const ICONS = {
  clock: "M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z",
  refresh:
    "M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7l4.029-1.523a.75.75 0 01.93.539v.011a.75.75 0 01-.539.93l-4.029 1.523a8.25 8.25 0 01-13.803 3.7l-3.182-3.182v-.001z",
  bolt: "M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z",
  list: "M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM3.75 12h.007v.008H3.75V12zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm-.375 5.25h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z",
  wallet:
    "M2.25 8.25h19.5m-16.5.75h12a2.25 2.25 0 012.25 2.25v3a2.25 2.25 0 01-2.25 2.25h-12A2.25 2.25 0 012.25 14.25v-3a2.25 2.25 0 012.25-2.25z",
  key: "M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z",
};

function fmtDay(value: string) {
  const d = new Date(`${value}T00:00:00`);
  return Number.isNaN(d.getTime())
    ? value
    : new Intl.DateTimeFormat("id-ID", {
        day: "2-digit",
        month: "short",
      }).format(d);
}

function StatusBadge({ code }: { code: number }) {
  if (code >= 200 && code < 300) return <Badge tone="success">{code}</Badge>;
  if (code >= 400 && code < 500) return <Badge tone="warning">{code}</Badge>;
  if (code >= 500) return <Badge tone="danger">{code}</Badge>;
  return <Badge tone="default">{code}</Badge>;
}

/** Sparkline kecil (SVG inline) dari requests per hari. */
function Sparkline({ data }: { data: DailyUsageRow[] }) {
  const values = data.map((d) => Number(d.requests));
  if (values.length === 0) return null;
  const W = 140;
  const H = 44;
  const pad = 3;
  const max = Math.max(1, ...values);
  const step = values.length > 1 ? (W - pad * 2) / (values.length - 1) : 0;
  const pts = values.map((v, i) => {
    const x = values.length > 1 ? pad + i * step : W / 2;
    const y = H - pad - (v / max) * (H - pad * 2);
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  });
  const line = pts.join(" ");
  const area = `${pad},${H - pad} ${line} ${W - pad},${H - pad}`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="h-11 w-36 shrink-0">
      <defs>
        <linearGradient id="sparkFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.35} />
          <stop offset="100%" stopColor="#3b82f6" stopOpacity={0} />
        </linearGradient>
      </defs>
      <polygon points={area} fill="url(#sparkFill)" />
      <polyline
        points={line}
        fill="none"
        stroke="#3b82f6"
        strokeWidth={2}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** Tooltip grafik tren dengan satu metrik aktif. */
function TrendTooltip({ active, payload, metric }: any) {
  if (!active || !payload?.length) return null;
  const row = payload[0].payload as DailyUsageRow;
  const meta = TREND[metric as TrendMetric];
  const raw = Number(
    (row as unknown as Record<string, unknown>)[meta.key] ?? 0,
  );
  const d = new Date(`${row.date}T00:00:00`);
  const label = Number.isNaN(d.getTime())
    ? row.date
    : new Intl.DateTimeFormat("id-ID", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      }).format(d);
  return (
    <div className="rounded-xl border border-white/[0.08] bg-ink-900 px-3.5 py-2.5 text-xs shadow-modal">
      <p className="mb-1 font-semibold text-white">{label}</p>
      <p className="flex items-center justify-between gap-6 text-slate-400">
        <span className="flex items-center gap-1.5">
          <span
            className="h-2 w-2 rounded-full"
            style={{ background: meta.color }}
          />
          {meta.label}
        </span>
        <span className="font-semibold tabular-nums text-white">
          {metric === "requests" ? formatNumber(raw) : formatCompact(raw)}
        </span>
      </p>
    </div>
  );
}

function Metric({
  label,
  value,
  hint,
  icon,
  accent = "text-white",
}: {
  label: string;
  value: string;
  hint?: string;
  icon: string;
  accent?: string;
}) {
  return (
    <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] px-3 py-2.5">
      <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-slate-500">
        <svg
          className="h-3.5 w-3.5 shrink-0"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={1.7}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d={icon} />
        </svg>
        <span className="truncate">{label}</span>
      </div>
      <p className={`mt-1 text-base font-bold tabular-nums ${accent}`}>
        {value}
      </p>
      {hint && (
        <p className="mt-0.5 text-[10px] leading-snug text-slate-500">{hint}</p>
      )}
    </div>
  );
}

function SummaryBit({
  label,
  value,
  hint,
}: {
  label: string;
  value: string;
  hint?: string;
}) {
  return (
    <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2">
      <p className="text-[10px] font-semibold uppercase tracking-wider text-slate-500">
        {label}
      </p>
      <p className="mt-0.5 text-sm font-semibold tabular-nums text-white">
        {value}
      </p>
      {hint && <p className="text-[10px] text-slate-500">{hint}</p>}
    </div>
  );
}

export default function UsagePage() {
  const [days, setDays] = useState(30);
  const [limit, setLimit] = useState(50);
  const [trendMetric, setTrendMetric] = useState<TrendMetric>("requests");
  const [logFilter, setLogFilter] = useState<LogFilter>("all");

  const {
    data,
    loading,
    error,
    refresh: refreshUsage,
  } = useUsage(days);
  const {
    requests: logRequests,
    loading: logLoading,
    error: logError,
    refresh: refreshLog,
  } = useUsageRequests(days, limit);

  const periodLabel =
    days === 0 ? "semua waktu" : days === 1 ? "hari ini" : `${days} hari terakhir`;
  const busy = loading || logLoading;

  const refreshAll = () => {
    void refreshUsage();
    void refreshLog();
  };

  const totalTokens =
    Number(data?.usage.input_tokens ?? 0) +
    Number(data?.usage.cached_tokens ?? 0) +
    Number(data?.usage.output_tokens ?? 0);
  const requestsTotal = Number(data?.usage.requests ?? 0);
  const avgLatency = Number(data?.usage.avg_latency_ms ?? 0);
  const hasRequests = requestsTotal > 0;
  const activeDays = data?.daily.length ?? 0;
  const avgReqPerDay = activeDays > 0 ? requestsTotal / activeDays : 0;

  const peakDay = (data?.daily ?? []).reduce<DailyUsageRow | null>(
    (best, row) => (!best || Number(row.requests) > Number(best.requests) ? row : best),
    null,
  );

  const keyRequestsTotal = (data?.detail ?? []).reduce(
    (sum, row) => sum + Number(row.requests),
    0,
  );

  const walletRows = logRequests.filter(
    (r) => Number(r.covered_by_package) !== 1,
  ).length;
  const packageRows = logRequests.length - walletRows;
  const filteredRequests = logRequests.filter((r) => {
    if (logFilter === "all") return true;
    if (logFilter === "package") return Number(r.covered_by_package) === 1;
    return Number(r.covered_by_package) !== 1;
  });
  const logCounts: Record<LogFilter, number> = {
    all: logRequests.length,
    wallet: walletRows,
    package: packageRows,
  };

  const iconProps = {
    className: "h-5 w-5",
    fill: "none",
    viewBox: "0 0 24 24",
    stroke: "currentColor",
    strokeWidth: 1.7,
  } as const;

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <h2 className="text-xl font-bold tracking-tight text-white sm:text-2xl">
            Penggunaan
          </h2>
          <p className="mt-1 text-sm text-slate-500">
            Pemakaian request, token, biaya & latency pada akun Anda.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <div className="flex items-center gap-1 rounded-xl border border-white/[0.06] bg-white/[0.03] p-1">
            {PERIODS.map((p) => (
              <button
                key={p.value}
                onClick={() => setDays(p.value)}
                className={`rounded-lg px-3.5 py-1.5 text-xs font-medium transition-colors ${
                  days === p.value
                    ? "bg-white/[0.08] text-white"
                    : "text-slate-500 hover:text-slate-300"
                }`}
              >
                {p.label}
              </button>
            ))}
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={refreshAll}
            isLoading={busy}
          >
            Refresh
          </Button>
        </div>
      </div>

      {loading && !data && (
        <div className="space-y-5">
          <div className="h-56 animate-pulse rounded-2xl border border-white/[0.04] bg-white/[0.02]" />
          <div className="h-40 animate-pulse rounded-2xl border border-white/[0.04] bg-white/[0.02]" />
          <div className="h-80 animate-pulse rounded-2xl border border-white/[0.04] bg-white/[0.02]" />
        </div>
      )}

      {error && (
        <Card className="p-8 text-center text-sm text-red-300">
          Gagal memuat data penggunaan: {error}
        </Card>
      )}

      {data && (
        <>
          {/* Hero: ringkasan + 6 metrik */}
          <Card className="relative overflow-hidden">
            <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_55%_65%_at_85%_-10%,rgba(59,130,246,0.12),transparent)]" />
            <div className="relative p-5 sm:p-6">
              <div className="flex flex-wrap items-start justify-between gap-6">
                <div className="min-w-0">
                  <p className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-widest text-brand-300">
                    <svg {...iconProps} className="h-4 w-4">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z"
                      />
                    </svg>
                    Total Token
                  </p>
                  <p className="mt-2 text-4xl font-extrabold tracking-tight tabular-nums text-white sm:text-5xl">
                    {totalTokens.toLocaleString("id-ID")}
                  </p>
                  <p className="mt-1.5 text-xs text-slate-500">
                    token terpakai · {periodLabel}
                  </p>
                  <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[11px] text-slate-400">
                    <span>
                      <span className="font-semibold text-white">
                        {formatNumber(requestsTotal)}
                      </span>{" "}
                      request
                    </span>
                    <span className="text-slate-700">·</span>
                    <span>
                      <span className="font-semibold text-white">
                        {formatCompact(avgReqPerDay)}
                      </span>{" "}
                      req/hari
                    </span>
                    <span className="text-slate-700">·</span>
                    <span>
                      latency{" "}
                      <span className="font-semibold text-white">
                        {hasRequests ? `${formatCompact(avgLatency)} ms` : "—"}
                      </span>
                    </span>
                  </div>
                </div>
                <Sparkline data={data.daily} />
              </div>

              <div className="mt-5 grid grid-cols-2 gap-2.5 sm:grid-cols-3 xl:grid-cols-6">
                <Metric
                  label="Input"
                  value={formatCompact(Number(data.usage.input_tokens))}
                  hint="token prompt"
                  icon={ICONS.clock}
                />
                <Metric
                  label="Cached"
                  value={formatCompact(Number(data.usage.cached_tokens))}
                  hint="token cache"
                  icon={ICONS.refresh}
                  accent="text-sky-300"
                />
                <Metric
                  label="Output"
                  value={formatCompact(Number(data.usage.output_tokens))}
                  hint="token completion"
                  icon={ICONS.bolt}
                />
                <Metric
                  label="Requests"
                  value={formatNumber(requestsTotal)}
                  hint={`${formatCompact(avgReqPerDay)} / hari`}
                  icon={ICONS.list}
                />
                <Metric
                  label="Latency"
                  value={hasRequests ? `${formatCompact(avgLatency)} ms` : "—"}
                  hint="rata-rata per request"
                  icon={ICONS.clock}
                />
              </div>
            </div>
          </Card>

          {/* Grafik tren */}
          <Card>
            <CardHeader
              title="Tren Pemakaian"
              subtitle={`Per hari · ${periodLabel}`}
              action={
                <div className="flex rounded-lg border border-white/[0.06] bg-white/[0.02] p-0.5">
                  {(Object.keys(TREND) as TrendMetric[]).map((key) => (
                    <button
                      key={key}
                      type="button"
                      onClick={() => setTrendMetric(key)}
                      className={`rounded-md px-2.5 py-1 text-[11px] font-medium transition-colors ${
                        trendMetric === key
                          ? "bg-white/[0.08] text-white"
                          : "text-slate-500 hover:text-slate-300"
                      }`}
                    >
                      {TREND[key].label}
                    </button>
                  ))}
                </div>
              }
            />
            <CardBody>
              <div className="mb-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
                <SummaryBit
                  label="Total Request"
                  value={formatNumber(requestsTotal)}
                />
                <SummaryBit
                  label="Rata-rata/hari"
                  value={formatCompact(avgReqPerDay)}
                  hint={`${activeDays} hari aktif`}
                />
                <SummaryBit
                  label="Hari Tersibuk"
                  value={peakDay ? fmtDay(peakDay.date) : "—"}
                  hint={
                    peakDay
                      ? `${formatNumber(peakDay.requests)} request`
                      : undefined
                  }
                />
                <SummaryBit
                  label="Total Token"
                  value={formatCompact(totalTokens)}
                />
              </div>

              {data.daily.length === 0 ? (
                <div className="flex h-60 items-center justify-center text-sm text-slate-500">
                  Belum ada data penggunaan pada rentang ini.
                </div>
              ) : (
                <div className="h-60 w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <AreaChart
                      data={data.daily}
                      margin={{ top: 4, right: 4, left: 0, bottom: 0 }}
                    >
                      <defs>
                        <linearGradient
                          id="usageTrend"
                          x1="0"
                          y1="0"
                          x2="0"
                          y2="1"
                        >
                          <stop
                            offset="0%"
                            stopColor={TREND[trendMetric].color}
                            stopOpacity={0.35}
                          />
                          <stop
                            offset="100%"
                            stopColor={TREND[trendMetric].color}
                            stopOpacity={0}
                          />
                        </linearGradient>
                      </defs>
                      <CartesianGrid
                        strokeDasharray="3 3"
                        stroke="rgba(255,255,255,0.05)"
                        vertical={false}
                      />
                      <XAxis
                        dataKey="date"
                        tickFormatter={fmtDay}
                        tick={{ fill: "#475569", fontSize: 10 }}
                        axisLine={false}
                        tickLine={false}
                        minTickGap={24}
                      />
                      <YAxis
                        tick={{ fill: "#475569", fontSize: 11 }}
                        tickFormatter={formatCompact}
                        axisLine={false}
                        tickLine={false}
                        allowDecimals={false}
                      />
                      <Tooltip
                        content={<TrendTooltip metric={trendMetric} />}
                        cursor={{ stroke: "rgba(255,255,255,0.15)" }}
                      />
                      <Area
                        type="monotone"
                        dataKey={TREND[trendMetric].key}
                        name={TREND[trendMetric].label}
                        stroke={TREND[trendMetric].color}
                        strokeWidth={2}
                        fill="url(#usageTrend)"
                      />
                    </AreaChart>
                  </ResponsiveContainer>
                </div>
              )}
            </CardBody>
          </Card>

          {/* Model terpopuler + per API key */}
          <div className="grid grid-cols-1 gap-5 xl:grid-cols-2">
            <Card>
              <CardHeader
                title="Model Terpopuler"
                subtitle="Share request & biaya per model"
              />
              <CardBody className="space-y-2">
                {data.models.length === 0 ? (
                  <p className="py-8 text-center text-sm text-slate-500">
                    Belum ada data model.
                  </p>
                ) : (
                  data.models.slice(0, 6).map((m) => {
                    const req = Number(m.requests);
                    const share =
                      requestsTotal > 0 ? (req / requestsTotal) * 100 : 0;
                    return (
                      <div
                        key={m.model}
                        className="rounded-lg border border-white/[0.04] bg-white/[0.02] px-3 py-2"
                      >
                        <div className="flex items-center justify-between gap-3 text-xs">
                          <span className="truncate font-mono text-slate-200">
                            {m.model}
                          </span>
                          <span className="shrink-0 tabular-nums text-slate-400">
                            <span className="font-semibold text-white">
                              {formatNumber(req)}
                            </span>{" "}
                            req · {share.toFixed(1)}%
                          </span>
                        </div>
                        <div className="mt-1.5 flex items-center gap-2">
                          <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.04]">
                            <div
                              className="h-full rounded-full bg-gradient-to-r from-blue-500 to-blue-400"
                              style={{ width: `${share}%` }}
                            />
                          </div>
                          <span className="w-20 shrink-0 text-right text-[10px] tabular-nums text-slate-500">
                            {formatIDR(Number(m.cost))}
                          </span>
                        </div>
                      </div>
                    );
                  })
                )}
              </CardBody>
            </Card>

            <Card>
              <CardHeader
                title="Per API Key"
                subtitle={`Pemakaian ${periodLabel}`}
              />
              <CardBody className="space-y-2">
                {data.detail.length === 0 ? (
                  <p className="py-8 text-center text-sm text-slate-500">
                    Belum ada pemakaian.
                  </p>
                ) : (
                  data.detail.map((row) => {
                    const req = Number(row.requests);
                    const share =
                      keyRequestsTotal > 0 ? (req / keyRequestsTotal) * 100 : 0;
                    const tokens =
                      Number(row.input_tokens) +
                      Number(row.cached_tokens) +
                      Number(row.output_tokens);
                    return (
                      <div
                        key={row.api_key_id}
                        className="rounded-lg border border-white/[0.04] bg-white/[0.02] px-3 py-2"
                      >
                        <div className="flex items-center gap-2.5">
                          <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/[0.06] bg-white/[0.03] text-brand-300">
                            <svg
                              {...iconProps}
                              className="h-3.5 w-3.5"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                d={ICONS.key}
                              />
                            </svg>
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="truncate text-xs font-medium text-white">
                              {row.name}
                            </p>
                            <p className="truncate font-mono text-[10px] text-slate-600">
                              {row.key_prefix}
                            </p>
                          </div>
                          <div className="hidden text-right sm:block">
                            <p className="text-xs font-semibold tabular-nums text-white">
                              {formatNumber(req)} req
                            </p>
                            <p className="text-[10px] tabular-nums text-slate-500">
                              {formatCompact(tokens)} token
                            </p>
                          </div>
                          <div className="text-right">
                            <p className="text-xs font-semibold tabular-nums text-white">
                              {formatIDR(Number(row.cost))}
                            </p>
                            <p className="text-[10px] text-slate-500 sm:hidden">
                              {formatNumber(req)} req
                            </p>
                          </div>
                        </div>
                        <div className="mt-1.5 flex items-center gap-2">
                          <div className="h-1 flex-1 overflow-hidden rounded-full bg-white/[0.04]">
                            <div
                              className="h-full rounded-full bg-brand-400"
                              style={{ width: `${share}%` }}
                            />
                          </div>
                          <span className="w-9 shrink-0 text-right text-[10px] tabular-nums text-slate-500">
                            {share.toFixed(0)}%
                          </span>
                        </div>
                      </div>
                    );
                  })
                )}
              </CardBody>
            </Card>
          </div>
        </>
      )}

      {/* Log permintaan */}
      <Card>
        <CardHeader
          title="Log Permintaan"
          subtitle={`Rincian request ${
            days === 0 ? "semua waktu" : days === 1 ? "hari ini" : `${days} hari terakhir`
          }`}
          action={
            <select
              value={limit}
              onChange={(e) => setLimit(Number(e.target.value))}
              className="input-solid w-auto px-3 py-1.5 text-xs"
            >
              <option value={50}>50 baris</option>
              <option value={100}>100 baris</option>
              <option value={200}>200 baris</option>
            </select>
          }
        />
        <CardBody className="p-0">
          <div className="flex flex-wrap items-center gap-1.5 border-b border-white/[0.06] px-4 py-2.5">
            {LOG_FILTERS.map((f) => (
              <button
                key={f.value}
                type="button"
                onClick={() => setLogFilter(f.value)}
                className={`rounded-md px-2.5 py-1 text-[11px] font-medium transition-colors ${
                  logFilter === f.value
                    ? "bg-white/[0.08] text-white"
                    : "text-slate-500 hover:text-slate-300"
                }`}
              >
                {f.label}
                <span className="ml-1 tabular-nums text-slate-500">
                  {logCounts[f.value]}
                </span>
              </button>
            ))}
            <span className="ml-auto text-[10px] tabular-nums text-slate-500">
              {filteredRequests.length} dari {logRequests.length} baris
            </span>
          </div>

          {logError && (
            <div className="p-5 text-sm text-red-300">
              Gagal memuat log: {logError}
            </div>
          )}
          {logLoading && logRequests.length === 0 ? (
            <div className="space-y-3 p-5">
              {[...Array(5)].map((_, i) => (
                <div
                  key={i}
                  className="h-12 animate-pulse rounded-xl bg-white/[0.02]"
                />
              ))}
            </div>
          ) : filteredRequests.length === 0 ? (
            <div className="px-5 py-10 text-center text-sm text-slate-500">
              {logRequests.length === 0
                ? "Belum ada permintaan pada rentang ini."
                : "Tidak ada permintaan pada filter ini."}
            </div>
          ) : (
            <div className="max-h-[560px] overflow-auto">
              <table className="w-full min-w-[900px] text-left text-sm">
                <thead className="sticky top-0 z-10">
                  <tr className="border-b border-white/[0.06] bg-ink-800 text-[11px] uppercase tracking-wider text-slate-500">
                    <th className="px-5 py-2.5 font-semibold">Waktu</th>
                    <th className="px-4 py-2.5 font-semibold">Model</th>
                    <th className="px-4 py-2.5 font-semibold">API Key</th>
                    <th className="px-4 py-2.5 text-right font-semibold">
                      Total Token
                    </th>
                    <th className="px-4 py-2.5 text-right font-semibold">
                      Biaya
                    </th>
                    <th className="px-4 py-2.5 text-right font-semibold">
                      Latency
                    </th>
                    <th className="px-5 py-2.5 text-right font-semibold">
                      Status
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {filteredRequests.map((r: UsageRequestRow) => (
                    <tr
                      key={r.id}
                      className="border-b border-white/[0.04] transition-colors last:border-0 hover:bg-white/[0.02]"
                    >
                      <td className="px-5 py-2.5 text-xs tabular-nums text-slate-400">
                        {formatDateTime(r.created_at)}
                      </td>
                      <td className="px-4 py-2.5">
                        {r.model ? (
                          <span className="font-mono text-xs text-slate-200">
                            {r.model}
                          </span>
                        ) : (
                          <span className="text-xs text-slate-600">—</span>
                        )}
                      </td>
                      <td className="px-4 py-2.5">
                        <p className="text-xs font-medium text-slate-200">
                          {r.key_name}
                        </p>
                        <p className="font-mono text-[11px] text-slate-600">
                          {r.key_prefix}
                        </p>
                      </td>
                      <td className="px-4 py-2.5 text-right font-medium tabular-nums text-slate-300">
                        {formatNumber(r.total_tokens)}
                      </td>
                      <td className="px-4 py-2.5 text-right font-medium tabular-nums text-slate-300">
                        {Number(r.covered_by_package) === 1 ? (
                          <span
                            title="Request ditanggung paket aktif — tidak ada biaya wallet"
                            className="inline-flex items-center gap-1 rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-300"
                          >
                            <svg
                              className="h-3 w-3"
                              fill="none"
                              viewBox="0 0 24 24"
                              stroke="currentColor"
                              strokeWidth={2}
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                              />
                            </svg>
                            Paket
                          </span>
                        ) : r.cost != null ? (
                          formatIDR(Number(r.cost))
                        ) : (
                          <span className="text-slate-600">—</span>
                        )}
                      </td>
                      <td className="px-4 py-2.5 text-right tabular-nums text-slate-400">
                        {r.latency_ms != null ? (
                          <span className="text-xs">
                            {formatNumber(r.latency_ms)} ms
                          </span>
                        ) : (
                          <span className="text-xs text-slate-600">—</span>
                        )}
                      </td>
                      <td className="px-5 py-2.5 text-right">
                        <StatusBadge code={r.http_status} />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardBody>
      </Card>
    </div>
  );
}

Zerion Mini Shell 1.0