"use client" import * as React from "react" import { Table, Settings, Shield, LogOut, FileText, RefreshCw, ExternalLink, AlertTriangle } from "lucide-react" import { Logo } from "./logo" import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, } from "@/components/ui/sidebar" import { Button } from "@/components/ui/button" import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { ApiClient, SYS_ADMINS_API, type TableMetadata, type Admin } from "@/lib/api" import { applySchemaListMigration } from "@/lib/schema-migration" import { DatabaseSection } from "./database/database-section" import { AdminsSection } from "./admins/admins-section" import { SettingsSection } from "./settings/settings-section" import { LogsSection } from "./logs/logs-section" import { SyncSection } from "./sync/sync-section" import { useToast } from "@/hooks/use-toast" import { ThemeToggle } from "./theme-toggle" import { useNavigate, useLocation } from "react-router-dom" import { useAuth } from "@/lib/auth" import { getDashboardSection, ROUTES } from "@/lib/routes" import { cn } from "@/lib/utils" export function AdminDashboard() { const [mounted, setMounted] = React.useState(false) const [tables, setTables] = React.useState([]) const [admins, setAdmins] = React.useState([]) const [loading, setLoading] = React.useState(true) const [authErrorDialog, setAuthErrorDialog] = React.useState(false) const [authErrorReason, setAuthErrorReason] = React.useState("") // Auth error reason const { toast } = useToast() const navigate = useNavigate() const location = useLocation() const { logout, refreshSession } = useAuth() const showError = React.useCallback( (error: string, type: "error" | "warning" = "error") => { try { // Prevent error toasts for auth errors (401/403) - these are handled by the auth dialog const errorLower = error.toLowerCase() if ( errorLower.includes("unauthorized") || errorLower.includes("forbidden") || errorLower.includes("auth") || errorLower.includes("403") || errorLower.includes("401") ) { return // Don't show toast for auth errors, handle with dialog } toast({ variant: type === "error" ? "destructive" : "default", title: type === "error" ? "Error" : "Warning", description: error, duration: 10000, }) } catch (toastError) { console.warn("Failed to show error toast:", toastError) } }, [toast], ) const handleUnauthorized = React.useCallback(async (reason?: string | "") => { try { const stillAuthenticated = await refreshSession() if (stillAuthenticated) { return } setAuthErrorReason(reason || "") setAuthErrorDialog(true) } catch (error) { console.warn("Failed to handle unauthorized:", error) } }, [refreshSession]) const [apiClient, setApiClient] = React.useState( () => new ApiClient(handleUnauthorized, showError), ) React.useEffect(() => { setMounted(true) loadData() }, []) // Update API client when mode or settings change React.useEffect(() => { const newApiClient = new ApiClient(handleUnauthorized, showError) setApiClient(newApiClient) }, [handleUnauthorized, showError]) const loadAdmins = React.useCallback(async () => { if (!apiClient) return try { const adminsData = await apiClient.call(`${SYS_ADMINS_API}`) // Ensure adminsData is an array - handle paginated response let adminsArray: Admin[] = [] if (Array.isArray(adminsData)) { // Fallback: if response is directly an array (shouldn't happen with new API) adminsArray = adminsData } else if (adminsData?.items && Array.isArray(adminsData.items)) { // Paginated response: extract items from data object adminsArray = adminsData.items } else if (adminsData?.data?.items && Array.isArray(adminsData.data.items)) { // If data is nested adminsArray = adminsData.data.items } setAdmins(adminsArray) } catch (error) { console.error("Failed to load admins:", error) } }, [apiClient]) // Load admins when navigating to the admins page React.useEffect(() => { if (getDashboardSection(location.pathname) === "admins") { loadAdmins() } }, [location.pathname, loadAdmins]) const loadData = async () => { try { setLoading(true) // Only load tables on initial load const tablesData = await apiClient.call("/api/v1/schemas") // Ensure tablesData is an array - handle different response structures let tablesArray: TableMetadata[] = [] if (Array.isArray(tablesData)) { tablesArray = tablesData } else if (tablesData?.data && Array.isArray(tablesData.data)) { tablesArray = tablesData.data } const migratedTables = await applySchemaListMigration(apiClient, tablesArray) setTables(migratedTables) } catch (error) { console.error("Failed to load data:", error) } finally { setLoading(false) } } const handleLogout = async () => { try { await logout() navigate(ROUTES.login, { replace: true }) } catch (error) { console.warn("Failed to logout:", error) } } const handleAuthErrorLogin = () => { try { setAuthErrorDialog(false) // Always navigate to login and discard token, regardless of button clicked handleLogout() } catch (error) { console.warn("Failed to handle auth error login:", error) } } const handleAuthErrorDialogClose = (open: boolean) => { // If dialog is being closed (either by Cancel or X button), navigate to login if (!open) { handleAuthErrorLogin() } } const sidebarItems = [ { title: "Entities", icon: Table, id: "entities", path: ROUTES.entities, }, { title: "Logs", icon: FileText, id: "logs", path: ROUTES.logs, }, { title: "Admins", icon: Shield, id: "admins", path: ROUTES.admins, }, { title: "Settings", icon: Settings, id: "settings", path: ROUTES.settings, }, ] const currentSection = getDashboardSection(location.pathname) if (!mounted) { return (

Loading MantisBase Admin Dashboard...

) } return (
{sidebarItems.map((item) => ( navigate(item.path)} isActive={currentSection === item.id} style={{ height: "4rem", minHeight: "4rem" }} className={cn( "w-full justify-center p-0 mx-0 rounded-none border-l-2 border-transparent min-w-full", currentSection === item.id && "border-l-primary bg-accent" )} > {item.title}

{item.title}

))}

Toggle Theme

Documentation

Documentation

Logout

Logout

{loading ? (

Loading...

) : ( <> {currentSection === "entities" && ( )} {currentSection === "admins" && ( )} {currentSection === "logs" && } {currentSection === "sync" && } {currentSection === "settings" && } )}
{/* Auth Error Dialog */} Authentication Required Your session has expired or you don't have permission to access this resource. You will be redirected to the login page. {authErrorReason.length > 0 && (

API Response:

{authErrorReason}

)}
) }