import { useEffect, useState } from 'react'; import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis, } from 'recharts'; import { Card } from '@/components/ui/Card'; import { vpsApi } from '@/services/vpsApi'; type TrafficMode = | 'wireguard' | 'udp2raw'; type NetworkTrafficChartProps = { title?: string; subtitle?: string; mode?: TrafficMode; compact?: boolean; }; type TrafficPoint = { time: string; downloadMbps: number; uploadMbps: number; }; const MAX_POINTS = 24; export function NetworkTrafficChart({ title = 'Tráfego de Rede', subtitle = 'Débito RX/TX em direto', mode = 'wireguard', compact = false, }: NetworkTrafficChartProps) { const [points, setPoints] = useState< TrafficPoint[] >([]); const [error, setError] = useState(''); useEffect(() => { let mounted = true; async function loadTraffic() { try { const response = mode === 'udp2raw' ? await vpsApi.udp2rawTraffic() : await vpsApi.networkTraffic(); if (!mounted) { return; } const point: TrafficPoint = { time: new Date( response.updatedAt, ).toLocaleTimeString(), downloadMbps: response.downloadMbps, uploadMbps: response.uploadMbps, }; setPoints((currentPoints) => [ ...currentPoints.slice( -(MAX_POINTS - 1), ), point, ]); setError(''); } catch (err) { if (mounted) { setError(String(err)); } } } setPoints([]); setError(''); loadTraffic(); const intervalId = window.setInterval( loadTraffic, 3000, ); return () => { mounted = false; window.clearInterval(intervalId); }; }, [mode]); const latestPoint = points[points.length - 1]; return (

{title}

{subtitle}

3s
{error && (
{error}
)} {compact && latestPoint && (

Entrada

{latestPoint.downloadMbps.toFixed(3)} Mbps

Saída

{latestPoint.uploadMbps.toFixed(3)} Mbps

)}
`${value} Mbps` } /> [ `${Number(value).toFixed( 3, )} Mbps`, '', ]} />
); }