"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Loader2, Plus } from "lucide-react"; import { getAdminUsers, getViewAsHeaders, startViewAsUser, unlockUser, type ManagedUser } from "@/lib/admin-api"; import { HelpTrigger } from "@/components/help/HelpTrigger"; import ExternalAccountModal from "@/components/admin/ExternalAccountModal"; import { getColumns } from "./columns"; import CompanyCard, { CompanyGroup } from "./CompanyCard"; import { EmptyState } from "./EmptyState"; export default function UserAccountsPage() { const router = useRouter(); const [mounted, setMounted] = useState(false); const [role, setRole] = useState(null); const [currentUsername, setCurrentUsername] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const [managedUsers, setManagedUsers] = useState([]); const [isModalOpen, setIsModalOpen] = useState(false); const [modalUser, setModalUser] = useState(null); const [targetCompany, setTargetCompany] = useState(null); const [viewAsLoading, setViewAsLoading] = useState(null); const [unlockLoading, setUnlockLoading] = useState(null); const [agentRegistry, setAgentRegistry] = useState>({}); const loadData = async () => { setIsLoading(true); setError(null); try { const users = await getAdminUsers(); setManagedUsers(users); } catch (err: any) { setError(err.message || "Failed to retrieve user data."); } finally { setIsLoading(false); } }; useEffect(() => { setMounted(true); document.title = "User Accounts | BackOne - Deep Package Inspection"; fetch("/api/auth/me", { headers: getViewAsHeaders() }) .then(res => res.json()) .then(data => { if (data.user) { const userRole = data.user.role || null; setRole(userRole); setCurrentUsername(data.user.username || null); if (userRole !== "SUPER_ADMIN" && userRole !== "EXECUTIVE" && userRole !== "COMPANY_ADMIN") { router.push("/"); } else { loadData(); fetch("/api/dashboard/agents/list", { headers: getViewAsHeaders() }) .then(r => r.json()) .then(json => { if (json.ok && Array.isArray(json.data)) { const map: Record = {}; json.data.forEach((a: any) => { if (a.uuid) map[a.uuid] = a.label || a.uuid; }); setAgentRegistry(map); } }) .catch(() => {}); } } else { setIsLoading(false); } }) .catch(() => { setIsLoading(false); }); }, [router]); if (!mounted) return null; const COMPANY_ROLES = ['COMPANY_ADMIN', 'COMPANY_OPERATOR', 'COMPANY_VIEWER']; const companyUsers = managedUsers.filter(u => COMPANY_ROLES.includes(u.role || '') && u.company_name); const companiesMap: Record = {}; companyUsers.forEach(u => { if (u.company_name) { if (!companiesMap[u.company_name]) { companiesMap[u.company_name] = []; } companiesMap[u.company_name].push(u); } }); const companies: CompanyGroup[] = Object.entries(companiesMap).map(([name, users]) => ({ name, users })); const handleEditClick = (user: ManagedUser) => { setModalUser(user); setTargetCompany(user.company_name || null); setIsModalOpen(true); }; const handleAddUserClick = (companyName: string) => { setModalUser(null); setTargetCompany(companyName); setIsModalOpen(true); }; const handleViewAsUser = async (user: ManagedUser) => { const agentUuids = user.agent_uuids || []; if (agentUuids.length === 0) { alert(`User "${user.account_name || user.username}" has no assigned agents. Cannot enter View-As mode.`); return; } const targetAgentUuid = agentUuids[0]; const agentLabel = agentRegistry[targetAgentUuid] || targetAgentUuid; const userName = user.account_name || user.username; const userRole = user.role; setViewAsLoading(user.username); try { await startViewAsUser(targetAgentUuid, agentLabel, userName, userRole, user.id); router.refresh(); window.location.reload(); } catch (err: any) { alert('Failed to enter View As mode: ' + err.message); } finally { setViewAsLoading(null); } }; const handleUnlockUser = async (user: ManagedUser) => { setUnlockLoading(user.id); try { const res = await unlockUser(user.id); if (res.ok) { await loadData(); } else { alert('Failed to unlock user: ' + (res.error || 'Unknown error')); } } catch (err: any) { alert('Failed to unlock user: ' + err.message); } finally { setUnlockLoading(null); } }; const columns = getColumns({ role, currentUsername, viewAsLoading, unlockLoading: unlockLoading !== null ? String(unlockLoading) : null, onEditClick: handleEditClick, onViewAsClick: (role === "SUPER_ADMIN" || role === "COMPANY_ADMIN") ? handleViewAsUser : undefined, onUnlockClick: (role === "SUPER_ADMIN" || role === "COMPANY_ADMIN" || role === "TENANT_ADMIN") ? handleUnlockUser : undefined, }); return (

User Accounts Directory {isLoading && }

{/* Mobile Actions: Inline next to Title */}

Manage company tenant user access, roles, and device ownership delegation.

{/* Laptop/Tablet Actions: Floats on the right */}
{error && (
{error}
)} {isLoading ? (
) : (
{companies.length === 0 ? ( ) : ( companies.map((company) => ( )) )} {role === "SUPER_ADMIN" && companies.length > 0 && (
)}
)} { setIsModalOpen(false); setModalUser(null); setTargetCompany(null); }} onSuccess={() => { setIsModalOpen(false); setModalUser(null); setTargetCompany(null); loadData(); }} user={modalUser} targetCompany={targetCompany} targetSiteUuid={null} targetCreatedBy={role === "SUPER_ADMIN" ? "admin" : undefined} />
); }