"use client"; import React, { useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; import { useStableState } from "@/hooks/useStableState"; import { useVisiblePolling } from "@/hooks/useVisiblePolling"; import { Calendar, Banknote, Gift, Users, Ticket, QrCode, ClipboardList, UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, } from "lucide-react"; import { StatCard, StatCardRow } from "@/components/shared/StatCard"; import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile"; import { AreaTrendChart } from "@/components/charts/AreaTrendChart"; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`; const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`; const formatCount = (n: number) => (n || 0).toLocaleString(); const REPORTS_URL = "/dashboard/supervisor/reports"; const QUICK_ACTIONS = [ { href: "/dashboard/admin/users", label: "Manage users", description: "Create, edit, change roles and passwords", icon: Users }, { href: "/dashboard/supervisor/events", label: "Manage events", description: "Create, edit, and update ticket types", icon: Calendar }, { href: "/dashboard/admin/registrations", label: "Manage registrations", description: "Cancel, update status, and search registrations", icon: ClipboardList }, { href: "/dashboard/supervisor/manual", label: "Manual registration", description: "Register a guest and issue tickets", icon: UserPlus }, { href: "/dashboard/supervisor/at-the-door", label: "At the door", description: "Walk-ins, payments, ticket printing", icon: DoorOpen }, { href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet }, { href: "/dashboard/staff/ticket-scanning", label: "Open scanner", description: "Use your device camera to validate tickets", icon: QrCode }, { href: "/dashboard/supervisor/reports", label: "Reports", description: "View, export, and email reports", icon: BarChart2 }, { href: "/dashboard/admin/forms", label: "Attendee forms", description: "View submitted attendee forms", icon: FileText }, { href: "/dashboard/supervisor/email-attendees", label: "Email attendees", description: "Send a message to attendees of an event", icon: Mail }, { href: "/dashboard/supervisor/whatsapp-attendees", label: "WhatsApp attendees", description: "Send a WhatsApp message to event attendees", icon: MessageCircle }, { href: "/dashboard/admin/cashup", label: "Post-event Cashup", description: "Set costs, reconcile takings, and close out events", icon: Wallet }, ] as const; type OverviewMetric = { thisMonth: number; lastMonth: number; pctChange: number | null }; type Overview = { activeEvents: number; registrations: OverviewMetric; ticketsSold: OverviewMetric; revenue: OverviewMetric; donations: OverviewMetric; trend: { date: string; revenue: number }[]; topEvents: { eventId: string; title: string; revenue: number; registrations: number; ticketsSold: number }[]; }; export default function AdminDashboardPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const isAdmin = useMemo(() => (user?.role === "admin"), [user]); useEffect(() => { if (loading) return; if (!user) router.replace("/login"); }, [user, loading, router]); // /api/stats/admin covers today/week/month payment totals (unchanged from before); // /api/stats/overview is the month-over-month KPI/trend/top-events endpoint. Both are // computed server-side — no full payments/events list ever ships to the client. const [paymentStats, setPaymentStats] = useStableState(null); const [overview, setOverview] = useStableState(null); const [loadingStats, setLoadingStats] = useState(false); const hasLoadedOnce = useRef(false); const [paymentsTab, setPaymentsTab] = useState<"today" | "week" | "month">("today"); const loadStats = async () => { if (!token) return; const isFirstLoad = !hasLoadedOnce.current; try { if (isFirstLoad) setLoadingStats(true); const [dash, overviewData] = await Promise.all([ apiFetch("/api/stats/admin", { authToken: token }), apiFetch("/api/stats/overview", { authToken: token }), ]); setPaymentStats(dash.paymentStats); setOverview(overviewData); } catch (e) { // ignore errors for dashboard summaries } finally { hasLoadedOnce.current = true; if (isFirstLoad) setLoadingStats(false); } }; useEffect(() => { if (!token) return; loadStats(); }, [token]); // Poll every 15s while the tab is visible; pause in the background and refetch // immediately on return instead of leaving stale numbers up. useVisiblePolling(() => { if (!token) return; loadStats(); }, 15000, !!token); const paymentsTabValue = paymentStats ? paymentsTab === "today" ? paymentStats.totalToday : paymentsTab === "week" ? paymentStats.totalWeek : paymentStats.totalMonth : 0; return (

Welcome back{user ? `, ${user.name}` : ""} 👋

Here's what's happening with your events today.

{!isAdmin && (
You need admin access to use these tools.
)}
Quick actions
{QUICK_ACTIONS.map(a => ( ))}

Revenue trend — past month

{overview && overview.trend.length > 0 ? ( ({ label: t.date.slice(5), value: t.revenue }))} valueFormatter={formatRand} axisFormatter={formatRandAxis} /> ) : (
No revenue recorded in the past month.
)}

Top performing events

{overview && overview.topEvents.length > 0 ? ( Event Registrations Revenue Tickets sold {overview.topEvents.map(e => ( {e.title} {formatCount(e.registrations)} {formatRand(e.revenue)} {formatCount(e.ticketsSold)} ))}
) : (
No event revenue recorded yet.
)}

Payments overview

{loadingStats && Refreshing…}
{(["today", "week", "month"] as const).map(t => ( ))}
{paymentStats ? (
{formatRand(paymentsTabValue)}
) : (
No payment data yet.
)}

As an admin you can access Supervisor and Staff tools. Use the quick actions above to jump to common tasks.

); }