import { useState } from 'react' import { useQuery } from '@tanstack/react-query' import { metricsApi } from '@/lib/api' import { TimeRangeSelector, getTimeRange, shouldAutoRefresh } from './TimeRangeSelector' import { TrafficChart } from './TrafficChart' interface InterfacesTabProps { tenantId: string deviceId: string active?: boolean } export function InterfacesTab({ tenantId, deviceId, active = true }: InterfacesTabProps) { const [timeRange, setTimeRange] = useState('6h') const [selectedInterface, setSelectedInterface] = useState(null) const [customStart, setCustomStart] = useState('') const [customEnd, setCustomEnd] = useState('') const { data: interfaces } = useQuery({ queryKey: ['metrics', 'interface-list', deviceId], queryFn: () => metricsApi.interfaceList(tenantId, deviceId), enabled: active, }) const { data: trafficData, isLoading } = useQuery({ queryKey: ['metrics', 'traffic', deviceId, timeRange, selectedInterface, customStart, customEnd], queryFn: () => { const { start, end } = getTimeRange(timeRange, customStart, customEnd) return metricsApi.interfaces(tenantId, deviceId, start, end, selectedInterface ?? undefined) }, refetchInterval: shouldAutoRefresh(timeRange), enabled: active, }) const handleCustomRangeChange = (start: string, end: string) => { setCustomStart(start) setCustomEnd(end) } // Group traffic data by interface name const byInterface = new Map() if (trafficData) { for (const point of trafficData) { const key = point.interface if (!byInterface.has(key)) byInterface.set(key, []) byInterface.get(key)!.push(point) } } const interfaceNames = selectedInterface ? [selectedInterface] : [...byInterface.keys()] return (
{/* Controls row */}
{/* Interface filter */} {interfaces && interfaces.length > 0 && (
Interface:
)}
{/* Charts */} {isLoading ? (
{[0, 1, 2].map((i) => (
))}
) : !trafficData || trafficData.length === 0 ? (
{interfaces && interfaces.length === 0 ? 'No interfaces discovered for this device.' : 'No traffic data available for the selected time range.'}
) : (
{interfaceNames.map((ifaceName) => { const ifaceData = byInterface.get(ifaceName) ?? [] return (
) })}
)}
) }