"use client"; import { useState, useEffect, useCallback } from "react"; import PropTypes from "prop-types"; import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, } from "recharts"; import Card from "@/shared/components/Card"; const fmtTokens = (n) => { if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`; if (n >= 1000) return `${(n / 1000).toFixed(1)}K`; return String(n || 0); }; const fmtCost = (n) => `$${(n || 0).toFixed(4)}`; export default function UsageChart({ period = "7d" }) { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [viewMode, setViewMode] = useState("tokens"); const fetchData = useCallback(async () => { setLoading(true); try { const res = await fetch(`/api/usage/chart?period=${period}`); if (res.ok) { const json = await res.json(); setData(json); } } catch (e) { console.error("Failed to fetch chart data:", e); } finally { setLoading(false); } }, [period]); useEffect(() => { fetchData(); }, [fetchData]); const hasData = data.some((d) => d.tokens > 0 || d.cost > 0); return (
{loading ? (
Loading...
) : !hasData ? (
No data for this period
) : ( name === "tokens" ? [fmtTokens(value), "Tokens"] : [fmtCost(value), "Cost"] } /> {viewMode === "tokens" ? ( ) : ( )} )}
); } UsageChart.propTypes = { period: PropTypes.string, };