"use client"; import { useState, useEffect, useCallback, useMemo } from "react"; import Card from "./Card"; import { CardSkeleton } from "./Loading"; import { fmtCompact as fmt, fmtFull, fmtCost } from "@/shared/utils/formatting"; import { StatCard, ActivityHeatmap, DailyTrendChart, AccountDonut, ApiKeyDonut, ApiKeyTable, MostActiveDay7d, WeeklySquares7d, ModelTable, ProviderCostDonut, ModelOverTimeChart, ProviderTable, } from "./analytics"; // ============================================================================ // Main Component // ============================================================================ export default function UsageAnalytics() { const [range, setRange] = useState("30d"); const [analytics, setAnalytics] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchAnalytics = useCallback(async () => { try { setLoading(true); const res = await fetch(`/api/usage/analytics?range=${range}`); if (!res.ok) throw new Error("Failed to fetch"); const data = await res.json(); setAnalytics(data); setError(null); } catch (err) { setError((err as any).message); } finally { setLoading(false); } }, [range]); useEffect(() => { fetchAnalytics(); }, [fetchAnalytics]); const ranges = [ { value: "1d", label: "1D" }, { value: "7d", label: "7D" }, { value: "30d", label: "30D" }, { value: "90d", label: "90D" }, { value: "ytd", label: "YTD" }, { value: "all", label: "All" }, ]; const topModel = useMemo(() => { const models = analytics?.byModel || []; return models.length > 0 ? models[0].model : "—"; }, [analytics]); const topProvider = useMemo(() => { const providers = analytics?.byProvider || []; return providers.length > 0 ? providers[0].provider : "—"; }, [analytics]); const busiestDay = useMemo(() => { const wp = analytics?.weeklyPattern || []; if (!wp.length) return "—"; const max = wp.reduce((a, b) => (a.avgTokens > b.avgTokens ? a : b), wp[0]); return max.avgTokens > 0 ? max.day : "—"; }, [analytics]); const providerCount = useMemo(() => { return (analytics?.byProvider || []).length; }, [analytics]); if (loading && !analytics) return ; if (error) return Error: {error}; const s = analytics?.summary || {}; // ── Derived insight values ── const avgTokensPerReq = s.totalRequests > 0 ? Math.round(s.totalTokens / s.totalRequests) : 0; const costPerReq = s.totalRequests > 0 ? s.totalCost / s.totalRequests : 0; const ioRatio = s.completionTokens > 0 ? (s.promptTokens / s.completionTokens).toFixed(1) : "—"; return (
{/* Header + Time Range */}

analytics Usage Analytics

{ranges.map((r) => ( ))}
{/* Summary Cards — Row 1: Core metrics */}
{/* Summary Cards — Row 2: Derived insights */}
{/* Activity Heatmap + Weekly Widgets */}
{/* Token & Cost Trend + Provider Cost Donut */}
{/* Model Usage Over Time (stacked area) */} {/* Account Donut + API Key Donut */}
{/* Provider Breakdown Table */} {/* API Key Table */} {/* Model Breakdown Table */}
); }