"use client"; import DashboardLayout from "@/components/DashboardLayout"; import TablePagination from "@/components/TablePagination"; import { useTablePagination } from "@/lib/use-table-pagination"; import { useState, useEffect, useCallback, useRef } from "react"; import { Server, Container, Globe, Shield, TrendingUp, TrendingDown, Activity, AlertTriangle, CheckCircle, Clock, Zap, } from "lucide-react"; import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, } from "recharts"; import { metrics as metricsApi, servers as serversApi, containers as containersApi, DashboardOverview, DashboardLiveMetrics, AuditLog, } from "@/lib/api"; import type { Server as ServerInfo } from "@/lib/api"; import { useRequireAuth } from "@/lib/auth-state"; const CustomTooltip = ({ active, payload, label, valueSuffix = "", }: { active?: boolean; payload?: { name: string; value: number; color: string }[]; label?: string; valueSuffix?: string; }) => { if (active && payload && payload.length) { return (

{label}

{payload.map((p) => (

{p.name}:{" "} {p.value} {valueSuffix}

))}
); } return null; }; function formatUpdatedAt(value?: string) { if (!value) return "Waiting for live data"; const date = new Date(value); if (Number.isNaN(date.getTime())) return "Waiting for live data"; const diffSeconds = Math.max( 0, Math.floor((Date.now() - date.getTime()) / 1000), ); if (diffSeconds < 10) return "Updated just now"; if (diffSeconds < 60) return `Updated ${diffSeconds}s ago`; return `Updated ${Math.floor(diffSeconds / 60)}m ago`; } function DashboardContent() { const [overview, setOverview] = useState(null); const [serverData, setServerData] = useState([]); const [liveMetrics, setLiveMetrics] = useState( null, ); const refreshInFlightRef = useRef(false); const loadDashboardSnapshot = useCallback(async () => { const [overviewRes, serversRes, liveRes] = await Promise.all([ metricsApi.overview(), serversApi.list(), metricsApi.live(12), ]); return { overview: overviewRes.data, servers: serversRes.data ?? [], liveMetrics: liveRes.data, }; }, []); const refreshDashboardSources = useCallback( async (servers: ServerInfo[], shouldSyncContainers: boolean) => { const onlineServers = servers.filter( (server) => server.status === "ONLINE", ); await Promise.allSettled( onlineServers.map((server) => serversApi.refreshMetrics(server.id)), ); if (onlineServers.length > 0 && shouldSyncContainers) { await Promise.allSettled( onlineServers.map((server) => containersApi.sync({ serverId: server.id }), ), ); } }, [], ); useEffect(() => { let cancelled = false; let pollCount = 0; const run = async (shouldSyncContainers: boolean) => { try { const data = await loadDashboardSnapshot(); if (cancelled) return; setOverview(data.overview); setServerData(data.servers); setLiveMetrics(data.liveMetrics); if (refreshInFlightRef.current) return; refreshInFlightRef.current = true; void (async () => { try { await refreshDashboardSources(data.servers, shouldSyncContainers); if (cancelled) return; const refreshedData = await loadDashboardSnapshot(); if (cancelled) return; setOverview(refreshedData.overview); setServerData(refreshedData.servers); setLiveMetrics(refreshedData.liveMetrics); } catch { // Keep the last successful snapshot while background refresh recovers. } finally { refreshInFlightRef.current = false; } })(); } catch { if (!cancelled) { // Keep the previous successful snapshot when a poll fails. } } }; void run(true); const interval = setInterval(() => { pollCount += 1; void run(pollCount % 2 === 0); }, 30000); return () => { cancelled = true; clearInterval(interval); }; }, [loadDashboardSnapshot, refreshDashboardSources]); const stats = [ { label: "Active Servers", value: overview ? `${overview.servers.online}/${overview.servers.total}` : "—", icon: Server, color: "#3b82f6", trend: overview ? `${overview.servers.total - overview.servers.online} offline` : "", trendUp: true, sub: "Online servers", }, { label: "Containers", value: overview ? String(overview.containers.running) : "—", icon: Container, color: "#10b981", trend: overview ? `${overview.containers.total} total` : "", trendUp: true, sub: "Running", }, { label: "Domains & SSL", value: overview ? String(overview.domains.total) : "—", icon: Globe, color: "#8b5cf6", trend: overview ? `${overview.ssl.valid} valid certs` : "", trendUp: true, sub: "Active domains", }, { label: "SSL Certificates", value: overview ? String(overview.ssl.valid) : "—", icon: Shield, color: "#f59e0b", trend: "Valid", trendUp: true, sub: "Active certs", }, ]; const serverPagination = useTablePagination({ items: serverData, resetKey: serverData.length, }); return (
{/* Stat cards */}
{stats.map((stat) => { const Icon = stat.icon; return (
{/* Glow orb */}

{stat.label}

{stat.value}

{stat.sub}

{stat.trendUp ? ( ) : ( )} {stat.trend}
); })}
{/* Charts row */}
{/* CPU/RAM/Net Chart */}

Resource Usage

avg. across monitored servers •{" "} {formatUpdatedAt(liveMetrics?.updatedAt)}

{[ { label: "CPU", color: "#3b82f6" }, { label: "RAM", color: "#8b5cf6" }, { label: "Disk", color: "#10b981" }, ].map((l) => (
{l.label}
))}
} />
{/* Container stats bar chart */}

Containers

live status by server

} />
{/* Servers table + Activity */}
{/* Servers table */}

Servers

{serverData.length} servers registered

{serverPagination.paginatedItems.map((s) => { const cpu = s.metrics?.cpuPct ?? 0; const ram = s.metrics?.ramPct ?? 0; const statusLow = s.status.toLowerCase(); return ( ); })} {serverData.length === 0 && ( )}
Server Status CPU RAM Containers Uptime
{s.name}

{s.ip}

{statusLow === "online" && ( )} {s.status}
70 ? "#ef4444" : "var(--text-secondary)", }} > {cpu.toFixed(0)}%
70 ? "#ef4444" : cpu > 50 ? "#f59e0b" : "#3b82f6", }} />
80 ? "#ef4444" : "var(--text-secondary)", marginBottom: 3, }} > {ram.toFixed(0)}%
80 ? "#ef4444" : ram > 60 ? "#f59e0b" : "#8b5cf6", }} />
{s.containers ?? 0} {s.metrics?.uptimeSec ? (() => { const sec = Number(s.metrics!.uptimeSec); const d = Math.floor(sec / 86400); const h = Math.floor((sec % 86400) / 3600); return d > 0 ? `${d}d ${h}h` : `${h}h`; })() : "—"}
No servers registered
{/* */}
{/* Activity log */}

Activity

Recent system events

{(overview?.recentLogs ?? []).map((a: AuditLog) => { const isSuccess = a.level === "SUCCESS"; const isError = a.level === "ERROR"; const isWarning = a.level === "WARNING"; return (
{isSuccess && ( )} {isError && ( )} {isWarning && ( )} {!isSuccess && !isError && !isWarning && ( )}

{a.message}

{new Date(a.createdAt).toLocaleTimeString()} {a.server && <> · {a.server.name}}

); })} {(!overview || overview.recentLogs.length === 0) && (
No recent activity
)}
{/* Quick actions */}

Quick Actions

{[ { label: "Deploy Container", icon: Container, color: "#10b981", href: "/containers", }, { label: "Add Server", icon: Server, color: "#3b82f6", href: "/servers", }, { label: "Setup SSL", icon: Shield, color: "#8b5cf6", href: "/ssl", }, { label: "Open Terminal", icon: Activity, color: "#06b6d4", href: "/terminal", }, { label: "Add Domain", icon: Globe, color: "#f59e0b", href: "/domains", }, { label: "View Logs", icon: Zap, color: "#ef4444", href: "/logs", }, ].map((action) => { const Icon = action.icon; return ( { (e.currentTarget as HTMLElement).style.background = `${action.color}20`; (e.currentTarget as HTMLElement).style.transform = "translateY(-1px)"; }} onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = `${action.color}10`; (e.currentTarget as HTMLElement).style.transform = "translateY(0)"; }} > {action.label} ); })}
); } export default function DashboardPage() { const isAuthenticated = useRequireAuth(); if (!isAuthenticated) { return null; } return ; }