"use client"; import Link from "next/link"; import { useEffect, useMemo, useState } from "react"; import { Boxes, RefreshCcw, ShieldAlert, Store, Users2 } from "lucide-react"; import { NoPermissionState } from "@/components/auth/no-permission-state"; import { PostPreviewCard } from "@/components/dashboard/post-preview-card"; import { useSuperAdminSession } from "@/components/auth/session-context"; import { PageHeader } from "@/components/dashboard/page-header"; import { StatCard } from "@/components/dashboard/stat-card"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { EmptyState } from "@/components/ui/empty-state"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { useToast } from "@/components/ui/toast"; import { searchAdminUsers } from "@/lib/api/admin-users"; import { getItems } from "@/lib/api/core"; import { listModerationListings } from "@/lib/api/marketplace"; import { listModerationPosts } from "@/lib/api/posts"; import { getSuperAdminOverview, getSuperAdminRecentActivity } from "@/lib/api/superadmin"; import { refreshSuperAdmin } from "@/lib/auth/client"; import { formatCurrency, formatDateTime } from "@/lib/format"; import { SUPERADMIN_PERMISSIONS, hasPermission } from "@/lib/permissions"; import type { ApiPost, ApiUser, MarketplaceListing, MarketplaceResponse, PostsResponse, SuperAdminOverviewResponse, SuperAdminRecentActivityItem, SuperAdminRecentActivityResponse, UsersResponse, } from "@/types/api"; import type { StatMetric } from "@/types"; type DashboardSnapshot = { overview: SuperAdminOverviewResponse | null; users: ApiUser[]; latestPosts: ApiPost[]; listings: MarketplaceListing[]; recentActivity: SuperAdminRecentActivityItem[]; }; const EMPTY_USERS: UsersResponse = { items: [], data: [] }; const EMPTY_LISTINGS: MarketplaceResponse = { items: [], data: [] }; const EMPTY_POSTS: PostsResponse = { items: [], data: [] }; const EMPTY_ACTIVITY: SuperAdminRecentActivityResponse = { items: [] }; function ShortcutLink({ href, icon, label, }: { href: string; icon: React.ReactNode; label: string; }) { return ( {icon} {label} ); } export default function DashboardPage() { const { permissions } = useSuperAdminSession(); const [snapshot, setSnapshot] = useState({ overview: null, users: [], latestPosts: [], listings: [], recentActivity: [], }); const [loading, setLoading] = useState(true); const { toast } = useToast(); const canReadOverview = hasPermission(permissions, SUPERADMIN_PERMISSIONS.OVERVIEW_READ); const canReadAnalytics = hasPermission(permissions, SUPERADMIN_PERMISSIONS.ANALYTICS_READ); const canReadUsers = hasPermission(permissions, SUPERADMIN_PERMISSIONS.USERS_READ); const canModerateContent = hasPermission( permissions, SUPERADMIN_PERMISSIONS.CONTENT_MODERATE, ); const canManageMarketplace = hasPermission( permissions, SUPERADMIN_PERMISSIONS.MARKETPLACE_MANAGE, ); useEffect(() => { let active = true; const loadDashboard = async () => { if (!canReadOverview) { setLoading(false); return; } setLoading(true); try { const [overview, recentActivity, usersResponse, postsResponse, listingsResponse] = await Promise.all([ getSuperAdminOverview(), canReadAnalytics ? getSuperAdminRecentActivity({ limit: 8 }) : Promise.resolve(EMPTY_ACTIVITY), canReadUsers ? searchAdminUsers({ page: 1, limit: 8, sortBy: "createdAt", sortOrder: "desc" }) : Promise.resolve(EMPTY_USERS), canModerateContent ? listModerationPosts({ page: 1, limit: 6, sortBy: "createdAt", sortOrder: "desc" }) : Promise.resolve(EMPTY_POSTS), canManageMarketplace ? listModerationListings({ page: 1, limit: 6, sortBy: "createdAt", sortOrder: "desc" }) : Promise.resolve(EMPTY_LISTINGS), ]); if (!active) return; setSnapshot({ overview, recentActivity: recentActivity.items ?? [], users: getItems(usersResponse), latestPosts: getItems(postsResponse) as ApiPost[], listings: getItems(listingsResponse), }); } catch (error) { if (!active) return; toast({ title: "Failed to load dashboard", description: String(error), variant: "danger", }); } finally { if (active) setLoading(false); } }; void loadDashboard(); return () => { active = false; }; }, [canManageMarketplace, canModerateContent, canReadAnalytics, canReadOverview, canReadUsers, toast]); const metrics = snapshot.overview?.metrics; const listingValue = useMemo( () => snapshot.listings.reduce((sum, item) => sum + (item.price ?? 0), 0), [snapshot.listings], ); const dashboardMetrics: StatMetric[] = [ { id: "users", label: "Users", value: loading ? "..." : String(metrics?.usersCount ?? 0), delta: "Total user accounts on the platform", trend: "up", }, { id: "admins", label: "Admins", value: loading ? "..." : String(metrics?.adminsCount ?? 0), delta: "Administrative accounts under platform control", trend: "up", }, { id: "listings", label: "Marketplace", value: loading ? "..." : String(metrics?.marketplaceListingsCount ?? 0), delta: `Value of loaded listings ${formatCurrency(listingValue)}`, trend: "neutral", }, { id: "alerts", label: "Unread alerts", value: loading ? "..." : String(metrics?.unreadNotificationsCount ?? 0), delta: `${metrics?.flaggedPostsCount ?? 0} flagged posts and ${metrics?.flaggedCommentsCount ?? 0} flagged comments`, trend: (metrics?.unreadNotificationsCount ?? 0) > 0 ? "down" : "neutral", }, ]; const shortcuts = [ canReadUsers ? { key: "users", href: "/users", icon: , label: "Manage users", } : null, canManageMarketplace ? { key: "marketplace", href: "/marketplace", icon: , label: "Review marketplace", } : null, hasPermission(permissions, SUPERADMIN_PERMISSIONS.CONTENT_MODERATE) ? { key: "content", href: "/content", icon: , label: "Moderate content", } : null, hasPermission(permissions, SUPERADMIN_PERMISSIONS.SESSIONS_MANAGE) || hasPermission(permissions, SUPERADMIN_PERMISSIONS.AUDIT_READ) || hasPermission(permissions, SUPERADMIN_PERMISSIONS.OPS_READ) ? { key: "security", href: "/security", icon: , label: "Security and sessions", } : null, ].filter(Boolean) as Array<{ key: string; href: string; icon: React.ReactNode; label: string }>; if (!canReadOverview) { return (
); } return (
{ try { await refreshSuperAdmin(); toast({ title: "Session refreshed", description: "SuperAdmin cookies were refreshed successfully.", variant: "success", }); } catch (error) { toast({ title: "Refresh failed", description: String(error), variant: "danger", }); } }} > Refresh session } />
{dashboardMetrics.map((metric) => ( ))}
{canReadUsers ? ( Latest users View all {!snapshot.users.length ? ( ) : ( Name Email Role Status {snapshot.users.slice(0, 6).map((user) => ( {user.name ?? user.username ?? "-"} {user.email} {user.role ?? "user"} {user.isDisabled ? "Disabled" : "Active"} ))}
)}
) : null} Quick actions {shortcuts.length ? ( shortcuts.map((item) => ( )) ) : ( )}
{canModerateContent ? ( Latest posts Open moderation {!snapshot.latestPosts.length ? ( ) : (
{snapshot.latestPosts.slice(0, 4).map((post) => ( ))}
)}
) : null} {canManageMarketplace ? ( Latest marketplace listings Manage marketplace {!snapshot.listings.length ? ( ) : ( Title Category Store Price {snapshot.listings.slice(0, 5).map((listing) => ( {listing.title} {listing.listingCategory ?? "-"} {listing.storeName ?? "-"} {formatCurrency(listing.price, listing.currency ?? "SAR")} ))}
)}
) : null} {canReadAnalytics ? ( Recent activity Activity feeds {!snapshot.recentActivity.length ? ( ) : (
{snapshot.recentActivity.map((item, index) => (
{item.title}
{item.type}
{item.subtitle} • {formatDateTime(item.createdAt)}
))}
)}
) : null}
); }