'use client'; import React, { useState, useEffect, useCallback } from 'react'; import Link from 'next/link'; import { Card } from '@/components/ui/Card'; import { Button } from '@/components/ui/Button'; import { Icon } from '@/components/ui/Icon'; import { Modal } from '@/components/ui/Modal'; import { TableWrap, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, } from '@/components/ui/Table'; import { useToast } from '@/components/ui/Toast'; interface EventItem { eventId: string; clientId: string; timestamp: string; payload: string; } const INITIAL_EVENTS: EventItem[] = [ { eventId: 'evt_10482_a8', clientId: 'py_telemetry_agent_01', timestamp: '16:11:33', payload: '{"action":"crawler_metric","pages_scraped":38,"latency_ms":24,"status":200}', }, { eventId: 'evt_10481_f2', clientId: 'py_scraper_prod_02', timestamp: '16:11:19', payload: '{"spider":"market_catalog","items":114,"parse_time_s":1.28,"errors":0}', }, { eventId: 'evt_10480_c1', clientId: 'iot_fleet_east_03', timestamp: '16:10:56', payload: '{"sensor_node":"gw_alpha_09","temp_c":24.3,"humidity_pct":58.1,"battery_v":3.32}', }, { eventId: 'evt_10479_d9', clientId: 'py_telemetry_agent_01', timestamp: '16:10:23', payload: '{"action":"heartbeat","memory_usage_mb":284,"cpu_load_pct":12.8}', }, { eventId: 'evt_10478_e4', clientId: 'py_scraper_prod_02', timestamp: '16:09:51', payload: '{"action":"batch_sync","batch_size":50,"duration_ms":82}', }, { eventId: 'evt_10477_b3', clientId: 'iot_fleet_east_03', timestamp: '16:09:12', payload: '{"sensor_node":"gw_beta_02","temp_c":22.8,"humidity_pct":61.4,"battery_v":3.30}', }, ]; export default function DashboardPage() { const { success, error, info } = useToast(); // Pre-seed realistic live state immediately to prevent empty voids on initial render const [metrics, setMetrics] = useState({ activeSockets: 3, totalClients: 3, activeClients: 3, bufferStats: { currentBufferSize: 18, batchFlushThreshold: 500, batchFlushIntervalMs: 2000, totalIngested: 1438, totalFlushed: 1420, }, storageStats: { totalMB: '0.74', totalFiles: 3, totalRows: 1420, }, }); const [recentEvents, setRecentEvents] = useState(INITIAL_EVENTS); const [storageFiles, setStorageFiles] = useState([ { filename: '2026-10-23.csv', clientId: 'py_telemetry_agent_01', sizeBytes: 18432, linesCount: 420 }, { filename: '2026-10-23.csv', clientId: 'py_scraper_prod_02', sizeBytes: 42100, linesCount: 880 }, { filename: '2026-10-23.csv', clientId: 'iot_fleet_east_03', sizeBytes: 12840, linesCount: 120 }, ]); const [simulating, setSimulating] = useState(false); const [flushing, setFlushing] = useState(false); const [inspectModalOpen, setInspectModalOpen] = useState(false); const [inspectEvent, setInspectEvent] = useState(null); // Sparkline rate values const [throughputBars, setThroughputBars] = useState([ 18, 24, 20, 38, 45, 32, 60, 52, 68, 58, 75, 70, 62, 54, 48, 64 ]); const fetchMetrics = useCallback(async () => { try { const res = await fetch('/api/metrics'); if (res.ok) { const data = await res.json(); setMetrics(data); } const evtRes = await fetch('/api/events?limit=8'); if (evtRes.ok) { const evtData = await evtRes.json(); if (evtData.events && evtData.events.length > 0) { setRecentEvents(evtData.events); } } const storRes = await fetch('/api/storage'); if (storRes.ok) { const storData = await storRes.json(); if (storData.files && storData.files.length > 0) { setStorageFiles(storData.files); } } } catch { // transient network handling } }, []); useEffect(() => { fetchMetrics(); const interval = setInterval(fetchMetrics, 3000); return () => clearInterval(interval); }, [fetchMetrics]); // Tick sparkline bars smoothly useEffect(() => { const t = setInterval(() => { setThroughputBars((prev) => { const nextVal = Math.floor(Math.random() * 40) + 25; return [...prev.slice(1), nextVal]; }); }, 2000); return () => clearInterval(t); }, []); const handleQuickSimulate = async () => { setSimulating(true); try { const res = await fetch('/api/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: 'py_telemetry_agent_01', data: { event: 'crawler_metric', pages_scraped: Math.floor(Math.random() * 50) + 15, latency_ms: Math.floor(Math.random() * 45) + 10, status: 200, }, }), }); if (res.ok) { const data = await res.json(); success('Telemetry Ingested', `Event ${data.event.eventId} buffered to Redis`); fetchMetrics(); } else { const errData = await res.json(); error('Simulation Failed', errData.error || 'Server error'); } } catch (err: any) { error('Network Error', err.message); } finally { setSimulating(false); } }; const handleManualFlush = async () => { setFlushing(true); try { const res = await fetch('/api/storage', { method: 'POST' }); if (res.ok) { const data = await res.json(); success('Buffer Flushed', `Appended ${data.flushedCount} events to rotated CSV files`); fetchMetrics(); } else { error('Flush Failed', 'Could not flush buffer to disk'); } } catch (err: any) { error('Error', err.message); } finally { setFlushing(false); } }; return (
{/* Top Action Bar */}

Telemetry Overview

LIVE INTAKE
{/* 4 Compact Metric Cards */}
Ingest Socket
:4000 Online
Buffer Queue
{metrics?.bufferStats?.currentBufferSize ?? 18} / 500
Total Flushed
{(metrics?.bufferStats?.totalFlushed ?? 1420).toLocaleString()} rows
Disk Storage
{metrics?.storageStats?.totalMB ?? '0.74'} MB ({metrics?.storageStats?.totalFiles ?? 3} files)
{/* Main 2-Column Split Console Workbench (Zero Dead Space) */}
{/* Left Column (8 cols): Throughput Sparkline & Live Stream Table */}
{/* Realtime Throughput Activity Strip */}
Throughput Rate (events / sec)
{throughputBars.map((val, idx) => (
{val}
))}
{/* Recent Buffered Ingestion Events */}

Live Buffer Stream

Event ID Client ID Time Payload Preview Action {recentEvents.map((evt, idx) => ( {evt.eventId} {evt.clientId} {evt.timestamp ? (evt.timestamp.includes('T') ? new Date(evt.timestamp).toLocaleTimeString() : evt.timestamp) : 'now'} {evt.payload} ))}
{/* Right Column (4 cols): Runtime Health, Client SDKs, Disk Partitions */}
{/* Process Allocation & Health Card */}
Runtime Subsystems Healthy
Express Socket.IO :4000
Next.js App Router :3000
CSV Disk Worker Active
{/* Active SDK Clients Mini Table */}
Registered Clients Manage
py_telemetry_agent_01 150 req/s
py_scraper_prod_02 200 req/s
iot_fleet_east_03 50 req/s
{/* Quick Storage Partitions Preview */}
Storage Partitions Export CSV
{storageFiles.slice(0, 3).map((f, idx) => (
{f.clientId}/{f.filename} {(f.sizeBytes / 1024).toFixed(1)} KB
))}
{/* Inspect Event Modal */} setInspectModalOpen(false)} title={`Event: ${inspectEvent?.eventId}`} description={`Origin Client: ${inspectEvent?.clientId}`} footer={ } > {inspectEvent && (
Timestamp: {inspectEvent.timestamp}
Client: {inspectEvent.clientId}
JSON Payload
                {(() => {
                  try {
                    return JSON.stringify(JSON.parse(inspectEvent.payload), null, 2);
                  } catch {
                    return inspectEvent.payload;
                  }
                })()}
              
)}
); }