import React, { useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminApi } from '../../api/admin';
import { AppLayout } from '../../components/layout/AppLayout';
import { PageLoader } from '../../components/ui/LoadingSpinner';
import {
Shield,
Search,
Plus,
Trash2,
X,
ChevronDown,
Check,
Loader2,
AlertTriangle,
Crown,
UserX,
UserPlus,
Building2,
} from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import type { ApiUser, PlatformRole, CompanyRole } from '../../types';
const PLATFORM_ROLES: { value: PlatformRole; label: string; color: string }[] = [
{ value: 'super_admin', label: 'Super Admin', color: 'bg-red-100 text-red-700' },
{ value: 'admin', label: 'Admin', color: 'bg-orange-100 text-orange-700' },
{ value: 'partner', label: 'Partner', color: 'bg-blue-100 text-blue-700' },
{ value: 'user', label: 'User', color: 'bg-gray-100 text-gray-600' },
];
const COMPANY_ROLES: { value: CompanyRole; label: string; color: string }[] = [
{ value: 'owner', label: 'Owner', color: 'bg-purple-100 text-purple-700' },
{ value: 'admin', label: 'Admin', color: 'bg-indigo-100 text-indigo-700' },
{ value: 'manager', label: 'Manager', color: 'bg-emerald-100 text-emerald-700' },
{ value: 'rep', label: 'Rep', color: 'bg-amber-100 text-amber-700' },
{ value: 'viewer', label: 'Viewer', color: 'bg-slate-100 text-slate-600' },
];
function RoleBadge({ role }: { role: string }) {
const config = PLATFORM_ROLES.find((r) => r.value === role);
return (
<span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
{config?.label || role}
</span>
);
}
function PlatformRoleDropdown({
userId,
currentRole,
onRoleChange,
}: {
userId: number;
currentRole: string;
onRoleChange: (userId: number, newRole: PlatformRole) => void;
}) {
const [open, setOpen] = useState(false);
const [rect, setRect] = useState<DOMRect | null>(null);
const triggerRef = React.useRef<HTMLButtonElement>(null);
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: ({ userId, role }: { userId: number; role: PlatformRole }) =>
adminApi.updateUserRole(userId, role),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-super-admins'] });
setOpen(false);
},
});
React.useEffect(() => {
if (open && triggerRef.current) {
setRect(triggerRef.current.getBoundingClientRect());
}
}, [open]);
const handleChange = (newRole: PlatformRole) => {
if (newRole === currentRole) return;
onRoleChange(userId, newRole);
mutation.mutate({ userId, role: newRole });
};
const config = PLATFORM_ROLES.find((r) => r.value === currentRole);
const dropdownContent = (
<div
className="w-44 rounded-xl border border-surface-200 bg-white shadow-lg py-1.5"
style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.right - 176 : 0, zIndex: 100 }}
>
{PLATFORM_ROLES.map((role) => (
<button
key={role.value}
onClick={() => handleChange(role.value)}
className="flex w-full items-center gap-2 px-3 py-2 text-sm rounded-lg hover:bg-surface-50 mx-0.5"
>
{currentRole === role.value && <Check className="h-3.5 w-3.5 text-brand-600" />}
{role.value === 'super_admin' && <Crown className="h-3.5 w-3.5 text-red-500" />}
<span
className={currentRole === role.value ? 'text-brand-700 font-medium' : 'text-surface-700'}
>
{role.label}
</span>
</button>
))}
</div>
);
return (
<div className="relative">
<button
ref={triggerRef}
onClick={() => setOpen(!open)}
disabled={mutation.isPending}
className="inline-flex items-center gap-1 px-1.5 py-0.5 hover:bg-surface-100 rounded-lg disabled:opacity-50 min-w-[80px] justify-center"
>
{mutation.isPending ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<>
<span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
{config?.label || currentRole}
</span>
<ChevronDown className="h-3 w-3 text-surface-400 shrink-0" />
</>
)}
</button>
{open && (
<>
<div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
{createPortal(dropdownContent, document.body)}
</>
)}
</div>
);
}
function CompanyRoleDropdown({
userId,
currentRole,
onRoleChange,
}: {
userId: number;
currentRole: string | null;
onRoleChange: (userId: number, newRole: CompanyRole) => void;
}) {
const [open, setOpen] = useState(false);
const [rect, setRect] = useState<DOMRect | null>(null);
const triggerRef = React.useRef<HTMLButtonElement>(null);
const queryClient = useQueryClient();
const { data: companies } = useQuery({
queryKey: ['admin-organizations'],
queryFn: () => adminApi.getOrganizations(),
enabled: open && !currentRole,
});
const mutation = useMutation({
mutationFn: ({ userId, role, companyId }: { userId: number; role: CompanyRole; companyId?: number }) =>
adminApi.updateCompanyRole(userId, role, companyId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-super-admins'] });
queryClient.invalidateQueries({ queryKey: ['admin-organizations'] });
setOpen(false);
},
});
React.useEffect(() => {
if (open && triggerRef.current) {
setRect(triggerRef.current.getBoundingClientRect());
}
}, [open]);
const handleChange = (newRole: CompanyRole, companyId?: number) => {
onRoleChange(userId, newRole);
mutation.mutate({ userId, role: newRole, companyId });
};
const config = COMPANY_ROLES.find((r) => r.value === currentRole);
// No company assigned — show "Assign Company" button
if (!currentRole) {
const dropdownContent = (
<div
className="w-56 max-h-72 overflow-y-auto rounded-xl border border-surface-200 bg-white shadow-lg py-1.5"
style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.right - 224 : 0, zIndex: 100 }}
>
<div className="px-3 py-2 text-[10px] font-semibold uppercase text-surface-400 tracking-wider">Select Company</div>
{companies?.items && companies.items.length > 0 ? companies.items.map((company: { id: number; name: string }) => (
<div key={company.id}>
<button
onClick={() => setOpen(false)}
className="flex w-full items-center justify-between gap-2 px-3 py-2 text-sm rounded-lg hover:bg-surface-50 mx-0.5"
>
<div className="flex items-center gap-2 min-w-0">
<Building2 className="h-3.5 w-3.5 text-surface-400 shrink-0" />
<span className="text-surface-700 truncate">{company.name}</span>
</div>
</button>
<div className="ml-4 border-l-2 border-surface-100">
{COMPANY_ROLES.map((role) => (
<button
key={role.value}
onClick={() => handleChange(role.value, company.id)}
className="flex w-full items-center gap-2 pl-4 pr-3 py-1.5 text-xs rounded-lg hover:bg-surface-50 mx-0.5"
>
{role.value === 'owner' && <Crown className="h-3 w-3 text-amber-500" />}
<span className="text-surface-600">{role.label}</span>
</button>
))}
</div>
</div>
)) : (
<div className="px-3 py-4 text-xs text-surface-400 text-center">No companies available</div>
)}
</div>
);
return (
<div className="relative">
<button
ref={triggerRef}
onClick={() => setOpen(!open)}
disabled={mutation.isPending}
className="inline-flex items-center gap-1 rounded-full border border-blue-200 px-3 py-1 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50"
>
{mutation.isPending ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<>
<UserPlus className="h-3 w-3 shrink-0" />
Assign Company
</>
)}
</button>
{open && (
<>
<div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
{createPortal(dropdownContent, document.body)}
</>
)}
</div>
);
}
// Has company — show role dropdown
const dropdownContent = (
<div
className="w-40 rounded-xl border border-surface-200 bg-white shadow-lg py-1.5"
style={{ position: 'fixed', top: rect ? rect.bottom + 4 : 0, left: rect ? rect.right - 160 : 0, zIndex: 100 }}
>
{COMPANY_ROLES.map((role) => (
<button
key={role.value}
onClick={() => handleChange(role.value)}
className="flex w-full items-center gap-2 px-3 py-2 text-sm rounded-lg hover:bg-surface-50 mx-0.5"
>
{currentRole === role.value && <Check className="h-3.5 w-3.5 text-brand-600" />}
<span className={currentRole === role.value ? 'text-brand-700 font-medium' : 'text-surface-700'}>
{role.label}
</span>
</button>
))}
</div>
);
return (
<div className="relative">
<button
ref={triggerRef}
onClick={() => setOpen(!open)}
disabled={mutation.isPending}
className="inline-flex items-center gap-1 px-1.5 py-0.5 hover:bg-surface-100 rounded-lg disabled:opacity-50 min-w-[80px] justify-center"
>
{mutation.isPending ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<>
<span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${config?.color || 'bg-gray-100 text-gray-600'}`}>
{config?.label || currentRole}
</span>
<ChevronDown className="h-3 w-3 text-surface-400 shrink-0" />
</>
)}
</button>
{open && (
<>
<div className="fixed inset-0 z-[99]" onClick={() => setOpen(false)} />
{createPortal(dropdownContent, document.body)}
</>
)}
</div>
);
}
export function SuperAdminsPage() {
const [search, setSearch] = useState('');
const [showCreateModal, setShowCreateModal] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
const { user: currentUser } = useAuth();
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ['admin-super-admins'],
queryFn: () => adminApi.getUsers({ role: 'super_admin' }),
});
const users = data?.items ?? [];
const filtered = users.filter(
(user) =>
user.email.toLowerCase().includes(search.toLowerCase()) ||
user.fullName.toLowerCase().includes(search.toLowerCase())
);
const deleteMutation = useMutation({
mutationFn: (userId: number) => adminApi.deleteUser(userId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-super-admins'] });
setDeleteConfirm(null);
},
});
const createMutation = useMutation({
mutationFn: (d: {
email: string;
full_name?: string;
password: string;
role?: PlatformRole;
company_name?: string;
company_role?: CompanyRole;
}) => adminApi.createUser(d),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['admin-super-admins'] });
setShowCreateModal(false);
},
});
const handlePlatformRoleChange = useCallback((_userId: number, _newRole: PlatformRole) => {}, []);
const handleCompanyRoleChange = useCallback((_userId: number, _newRole: CompanyRole) => {}, []);
if (isLoading) {
return (
<AppLayout title="Super Admins">
<PageLoader />
</AppLayout>
);
}
return (
<AppLayout title="Super Admins">
{/* Header */}
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-xl sm:text-2xl font-bold text-surface-900">Super Admins</h1>
<p className="mt-1 text-sm text-surface-500">
{users.length} super admin{users.length !== 1 ? 's' : ''} with full system access
</p>
<div className="mt-2 flex items-center gap-2">
<div className="flex h-5 w-5 items-center justify-center rounded bg-red-100">
<Crown className="h-3 w-3 text-red-600" />
</div>
<span className="text-xs text-surface-500">
Super admins have unrestricted access to all organizations, users, and settings
</span>
</div>
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-surface-500" />
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search admins..."
className="w-full border border-surface-300 pl-9 pr-3 py-2.5 text-sm rounded-lg outline-none focus:border-brand-500 min-h-[44px] w-full sm:w-56"
/>
</div>
<button
onClick={() => setShowCreateModal(true)}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 min-h-[44px] w-full sm:w-auto"
>
<Plus className="h-4 w-4" />
Add Admin
</button>
</div>
</div>
{/* Warning Banner */}
<div className="mb-4 flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
<div>
<p className="text-sm font-medium text-amber-800">Elevated Privileges</p>
<p className="text-xs text-amber-600 mt-0.5">
Super admins can manage all organizations, users, integrations, and platform settings. Limit this role to trusted operators only.
</p>
</div>
</div>
{/* Users Table */}
{filtered.length === 0 ? (
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-surface-300 bg-surface-50 py-16">
{users.length === 0 ? (
<>
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-surface-100">
<Crown className="h-8 w-8 text-surface-300" />
</div>
<p className="mt-4 text-sm font-medium text-surface-700">No super admins yet</p>
<p className="mt-1 text-xs text-surface-500">Create a super admin to manage the platform</p>
</>
) : (
<>
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-surface-100">
<Search className="h-8 w-8 text-surface-300" />
</div>
<p className="mt-4 text-sm font-medium text-surface-700">No admins match your search</p>
</>
)}
</div>
) : (
<div className="rounded-xl border border-surface-200 bg-white">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-surface-200">
<th className="pb-3 pl-5 text-left font-medium text-surface-500">Admin</th>
<th className="pb-3 text-left font-medium text-surface-500">Platform Role</th>
<th className="pb-3 text-left font-medium text-surface-500">Company Role</th>
<th className="pb-3 text-left font-medium text-surface-500">Status</th>
<th className="pb-3 text-right font-medium text-surface-500 pr-2">Last Login</th>
<th className="pb-3 pr-5 w-10"></th>
</tr>
</thead>
<tbody className="divide-y divide-surface-100">
{filtered.map((user) => (
<tr key={user.id} className="hover:bg-surface-50">
<td className="py-3 pl-5 align-middle">
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-red-100 text-xs font-semibold text-red-700">
{user.fullName.charAt(0).toUpperCase()}
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-surface-900 truncate">{user.fullName}</p>
<p className="text-xs text-surface-500 truncate">{user.email}</p>
</div>
</div>
</td>
<td className="py-3 px-2 align-middle">
<div className="flex items-center">
<PlatformRoleDropdown
userId={user.id}
currentRole={user.role}
onRoleChange={handlePlatformRoleChange}
/>
</div>
</td>
<td className="py-3 px-2 align-middle">
<div className="flex items-center">
<CompanyRoleDropdown
userId={user.id}
currentRole={user.companyRole ?? null}
onRoleChange={handleCompanyRoleChange}
/>
</div>
</td>
<td className="py-3 px-2 align-middle">
<div className="flex items-center">
<span
className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
user.status === 'active'
? 'bg-emerald-100 text-emerald-700'
: 'bg-surface-200 text-surface-600'
}`}
>
<span className="mr-1 h-1.5 w-1.5 rounded-full shrink-0 bg-current" />
{user.status}
</span>
</div>
</td>
<td className="py-3 px-2 text-right text-surface-500 align-middle">
<span className="text-xs text-surface-500">{user.lastLogin ? new Date(user.lastLogin).toLocaleDateString() : 'Never'}</span>
</td>
<td className="py-3 pr-5 text-right align-middle">
{user.id !== currentUser?.id && (
<button
onClick={() => setDeleteConfirm(user.id)}
className="inline-flex items-center justify-center rounded-lg p-1.5 text-surface-400 hover:text-red-600 hover:bg-red-50 transition-colors"
title="Remove super admin"
>
<Trash2 className="h-4 w-4" />
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Create Modal */}
{showCreateModal && (
<CreateAdminModal
onClose={() => setShowCreateModal(false)}
onCreate={createMutation.mutate}
isPending={createMutation.isPending}
/>
)}
{/* Delete Confirm */}
{deleteConfirm && (
<DeleteConfirmModal
user={filtered.find((u) => u.id === deleteConfirm)!}
onConfirm={() => deleteMutation.mutate(deleteConfirm!)}
onClose={() => setDeleteConfirm(null)}
isPending={deleteMutation.isPending}
/>
)}
</AppLayout>
);
}
function CreateAdminModal({
onClose,
onCreate,
isPending,
}: {
onClose: () => void;
onCreate: (d: {
email: string;
full_name?: string;
password: string;
role?: PlatformRole;
company_name?: string;
company_role?: CompanyRole;
}) => void;
isPending: boolean;
}) {
const [email, setEmail] = useState('');
const [fullName, setFullName] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onCreate({ email, full_name: fullName, password, role: 'super_admin' });
};
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
<div className="relative w-full max-w-md rounded-xl bg-white shadow-xl">
<div className="flex items-center justify-between border-b border-surface-200 px-5 py-4">
<div className="flex items-center gap-2">
<Crown className="h-4 w-4 text-red-600" />
<h2 className="text-lg font-semibold text-surface-900">Add Super Admin</h2>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-surface-400 hover:text-surface-600 hover:bg-surface-100 transition-colors">
<X className="h-4 w-4" />
</button>
</div>
<div className="border-y border-amber-200 bg-amber-50 px-5 py-3">
<p className="text-xs text-amber-700">
This user will have full platform access including all organizations, users, and settings.
</p>
</div>
<form onSubmit={handleSubmit} className="p-5 space-y-4">
<div>
<label className="block text-sm font-medium text-surface-700 mb-1.5">Email *</label>
<input
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500"
placeholder="admin@example.com"
/>
</div>
<div>
<label className="block text-sm font-medium text-surface-700 mb-1.5">Full Name *</label>
<input
type="text"
required
value={fullName}
onChange={(e) => setFullName(e.target.value)}
className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500"
placeholder="Admin Name"
/>
</div>
<div>
<label className="block text-sm font-medium text-surface-700 mb-1.5">Password *</label>
<input
type="password"
required
minLength={8}
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-lg border border-surface-300 px-3 py-2 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500"
placeholder="Min 8 characters"
/>
</div>
<div className="flex justify-end gap-3 pt-2">
<button
type="button"
onClick={onClose}
className="rounded-lg border border-surface-300 px-4 py-2 text-sm font-medium text-surface-700 hover:bg-surface-50 min-h-[40px]"
>
Cancel
</button>
<button
type="submit"
disabled={isPending}
className="inline-flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50 min-h-[40px]"
>
{isPending && <Loader2 className="h-4 w-4 animate-spin" />}
<UserPlus className="h-4 w-4" />
Create Admin
</button>
</div>
</form>
</div>
</div>,
document.body
);
}
function DeleteConfirmModal({
user,
onConfirm,
onClose,
isPending,
}: {
user: ApiUser;
onConfirm: () => void;
onClose: () => void;
isPending: boolean;
}) {
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
<div className="relative w-full max-w-md rounded-xl bg-white shadow-xl">
<div className="flex items-center gap-3 border-b border-surface-200 px-5 py-4">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-red-100">
<UserX className="h-5 w-5 text-red-600" />
</div>
<div>
<h2 className="text-lg font-semibold text-surface-900">Remove Super Admin</h2>
<p className="text-sm text-surface-500">{user.email}</p>
</div>
</div>
<div className="p-5">
<div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 mb-4">
<p className="text-sm text-red-700">
This will permanently delete <strong>{user.fullName}</strong>'s account and revoke all platform access.
</p>
</div>
<p className="text-sm text-surface-600">
Consider demoting them to a Partner or User role instead if you want to keep their account.
</p>
<div className="flex justify-end gap-3 pt-4">
<button
onClick={onClose}
className="rounded-lg border border-surface-300 px-4 py-2 text-sm font-medium text-surface-700 hover:bg-surface-50 min-h-[40px]"
>
Cancel
</button>
<button
onClick={onConfirm}
disabled={isPending}
className="inline-flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50 min-h-[40px]"
>
{isPending && <Loader2 className="h-4 w-4 animate-spin" />}
Delete User
</button>
</div>
</div>
</div>
</div>,
document.body
);
}