Admin Dashboard Frontend (Phases 1-4) #3

Merged
stephen merged 7 commits from admin into main 2026-01-22 14:12:59 -07:00
10 changed files with 1438 additions and 117 deletions
Showing only changes of commit a05f99080c - Show all commits

View File

@ -1,10 +1,13 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Routes, Route, Link, useLocation, Navigate } from 'react-router-dom'; import { Routes, Route, Link, useLocation, Navigate } from 'react-router-dom';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Area, AreaChart, ScatterChart, Scatter, ComposedChart, ReferenceLine } from 'recharts'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Area, AreaChart, ScatterChart, Scatter, ComposedChart, ReferenceLine } from 'recharts';
import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List, LogOut, User, ChevronDown, ChevronUp, Settings } from 'lucide-react'; import { TrendingUp, TrendingDown, Home, DollarSign, Calendar, MapPin, Activity, AlertCircle, Star, RefreshCw, Wifi, WifiOff, Bell, Target, Filter, Search, ArrowUp, ArrowDown, Zap, Clock, Eye, LayoutGrid, List, LogOut, User, ChevronDown, ChevronUp, Settings, Shield } from 'lucide-react';
import useAuth from './hooks/useAuth'; import useAuth from './hooks/useAuth';
import ProtectedRoute from './components/ProtectedRoute'; import ProtectedRoute from './components/ProtectedRoute';
import AdminRoute from './components/AdminRoute';
import Login from './pages/Login'; import Login from './pages/Login';
import UserList from './pages/admin/UserList';
import UserDetail from './pages/admin/UserDetail';
const ApartmentDashboard = () => { const ApartmentDashboard = () => {
// Router // Router
@ -558,6 +561,15 @@ const ApartmentDashboard = () => {
> >
Analytics Analytics
</Link> </Link>
{user && user.role === 'admin' && (
<Link
to="/admin/users"
className={`flex items-center space-x-2 px-4 py-2 rounded-md ${location.pathname.startsWith('/admin') ? 'bg-violet-600 text-white' : 'bg-violet-100 text-violet-700 border border-violet-300 hover:bg-violet-200'}`}
>
<Shield className="w-4 h-4" />
<span>Admin</span>
</Link>
)}
</div> </div>
</div> </div>
@ -1271,6 +1283,18 @@ const ApartmentDashboard = () => {
</ProtectedRoute> </ProtectedRoute>
} /> } />
{/* Admin Routes */}
<Route path="/admin/users" element={
<AdminRoute>
<UserList />
</AdminRoute>
} />
<Route path="/admin/users/:id" element={
<AdminRoute>
<UserDetail />
</AdminRoute>
} />
{/* Catch-all redirect to overview */} {/* Catch-all redirect to overview */}
<Route path="*" element={<Navigate to="/" replace />} /> <Route path="*" element={<Navigate to="/" replace />} />
</Routes> </Routes>

View File

@ -0,0 +1,33 @@
import { Navigate, useLocation } from 'react-router-dom';
import useAuth from '../hooks/useAuth';
const AdminRoute = ({ children }) => {
const { user, loading } = useAuth();
const location = useLocation();
// Loading state during auth check
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="flex flex-col items-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-violet-600"></div>
<p className="mt-4 text-gray-600">Checking permissions...</p>
</div>
</div>
);
}
// Not authenticated - redirect to login
if (!user) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
// Not an admin - redirect to home
if (user.role !== 'admin') {
return <Navigate to="/" replace />;
}
return children;
};
export default AdminRoute;

View File

@ -0,0 +1,480 @@
import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Shield, ShieldOff, UserCheck, UserX, RefreshCw, AlertCircle, Clock, Activity } from 'lucide-react';
import useAuth from '../../hooks/useAuth';
const API_BASE = 'https://apartments.maverickapplications.com/api';
const UserDetail = () => {
const { id } = useParams();
const navigate = useNavigate();
const { user: currentUser } = useAuth();
// State
const [user, setUser] = useState(null);
const [recentActivity, setRecentActivity] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [actionLoading, setActionLoading] = useState(false);
// Confirmation dialogs
const [showStatusConfirm, setShowStatusConfirm] = useState(false);
const [showRoleConfirm, setShowRoleConfirm] = useState(false);
// Check if viewing own profile
const isOwnProfile = currentUser?._id === id;
// Fetch user details
const fetchUser = useCallback(async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
credentials: 'include'
});
if (!response.ok) {
if (response.status === 404) {
throw new Error('User not found');
}
throw new Error('Failed to fetch user details');
}
const data = await response.json();
setUser(data.data.user);
setRecentActivity(data.data.recentActivity || []);
} catch (err) {
console.error('Error fetching user:', err);
setError(err.message);
} finally {
setLoading(false);
}
}, [id]);
// Fetch on mount
useEffect(() => {
fetchUser();
}, [fetchUser]);
// Toggle user status (enable/disable)
const handleToggleStatus = async () => {
setActionLoading(true);
try {
const response = await fetch(`${API_BASE}/admin/users/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ isActive: !user.isActive })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to update user status');
}
const data = await response.json();
setUser(data.data.user);
setShowStatusConfirm(false);
} catch (err) {
console.error('Error toggling status:', err);
alert(err.message);
} finally {
setActionLoading(false);
}
};
// Toggle user role (promote/demote)
const handleToggleRole = async () => {
setActionLoading(true);
try {
const newRole = user.role === 'admin' ? 'user' : 'admin';
const response = await fetch(`${API_BASE}/admin/users/${id}/role`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ role: newRole })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to update user role');
}
const data = await response.json();
setUser(data.data.user);
setShowRoleConfirm(false);
} catch (err) {
console.error('Error toggling role:', err);
alert(err.message);
} finally {
setActionLoading(false);
}
};
// Format date helper
const formatDate = (dateStr) => {
if (!dateStr) return 'Never';
return new Date(dateStr).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
};
// Format datetime helper
const formatDateTime = (dateStr) => {
if (!dateStr) return 'Never';
return new Date(dateStr).toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
// Get activity action description
const getActivityDescription = (activity) => {
const actions = {
'LOGIN': 'Logged in',
'LOGOUT': 'Logged out',
'PAGE_VIEW': `Viewed ${activity.metadata?.path || 'a page'}`,
'API_CALL': `API call to ${activity.metadata?.endpoint || 'unknown'}`,
'ADMIN_ENABLE_USER': 'Enabled a user',
'ADMIN_DISABLE_USER': 'Disabled a user',
'ADMIN_PROMOTE_USER': 'Promoted a user to admin',
'ADMIN_DEMOTE_USER': 'Demoted a user from admin'
};
return actions[activity.action] || activity.action;
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50 p-6">
<div className="max-w-4xl mx-auto">
<div className="flex items-center justify-center py-12">
<RefreshCw className="w-8 h-8 animate-spin text-violet-600" />
<span className="ml-3 text-gray-600">Loading user details...</span>
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="space-y-6">
<button
onClick={() => navigate('/admin/users')}
className="flex items-center text-violet-600 hover:text-violet-700"
>
<ArrowLeft className="w-4 h-4 mr-2" />
Back to Users
</button>
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
<p className="text-red-700 mb-4">{error}</p>
<button
onClick={fetchUser}
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
>
Try Again
</button>
</div>
</div>
);
}
if (!user) {
return null;
}
return (
<div className="space-y-6">
{/* Back Button */}
<button
onClick={() => navigate('/admin/users')}
className="flex items-center text-violet-600 hover:text-violet-700"
>
<ArrowLeft className="w-4 h-4 mr-2" />
Back to Users
</button>
{/* User Profile Card */}
<div className="bg-white rounded-lg shadow-md p-6">
<div className="flex items-start justify-between">
<div className="flex items-center space-x-4">
{user.picture ? (
<img
src={user.picture}
alt={user.name}
className="w-20 h-20 rounded-full"
/>
) : (
<div className="w-20 h-20 rounded-full bg-gray-300 flex items-center justify-center">
<span className="text-2xl font-medium text-gray-600">
{user.name?.charAt(0)?.toUpperCase() || '?'}
</span>
</div>
)}
<div>
<h1 className="text-2xl font-bold text-gray-900">{user.name}</h1>
<p className="text-gray-600">{user.email}</p>
<div className="flex items-center space-x-2 mt-2">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
user.role === 'admin'
? 'bg-violet-100 text-violet-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{user.role}
</span>
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
user.isActive
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}
>
{user.isActive ? 'Active' : 'Disabled'}
</span>
</div>
</div>
</div>
<button
onClick={fetchUser}
className="p-2 text-gray-400 hover:text-gray-600"
title="Refresh"
>
<RefreshCw className="w-5 h-5" />
</button>
</div>
{/* User Stats */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6 pt-6 border-t">
<div>
<p className="text-sm text-gray-600">Login Count</p>
<p className="text-xl font-semibold">{user.loginCount || 0}</p>
</div>
<div>
<p className="text-sm text-gray-600">Created</p>
<p className="text-lg font-medium">{formatDate(user.createdAt)}</p>
</div>
<div>
<p className="text-sm text-gray-600">Last Login</p>
<p className="text-lg font-medium">{formatDateTime(user.lastLoginAt)}</p>
</div>
{user.disabledAt && (
<div>
<p className="text-sm text-gray-600">Disabled At</p>
<p className="text-lg font-medium text-red-600">{formatDateTime(user.disabledAt)}</p>
</div>
)}
</div>
{/* Google ID (for debugging) */}
<div className="mt-4 pt-4 border-t">
<p className="text-sm text-gray-500">
<span className="font-medium">Google ID:</span> {user.googleId}
</p>
</div>
</div>
{/* Actions Card */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-lg font-semibold mb-4">Actions</h2>
<div className="flex flex-wrap gap-4">
{/* Enable/Disable Button */}
<div className="relative group">
<button
onClick={() => setShowStatusConfirm(true)}
disabled={isOwnProfile || actionLoading}
className={`flex items-center space-x-2 px-4 py-2 rounded-md transition-colors ${
user.isActive
? 'bg-red-100 text-red-700 hover:bg-red-200'
: 'bg-green-100 text-green-700 hover:bg-green-200'
} disabled:opacity-50 disabled:cursor-not-allowed`}
>
{user.isActive ? (
<>
<UserX className="w-4 h-4" />
<span>Disable User</span>
</>
) : (
<>
<UserCheck className="w-4 h-4" />
<span>Enable User</span>
</>
)}
</button>
{isOwnProfile && (
<div className="absolute bottom-full left-0 mb-2 px-3 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
You cannot disable your own account
</div>
)}
</div>
{/* Promote/Demote Button */}
<div className="relative group">
<button
onClick={() => setShowRoleConfirm(true)}
disabled={isOwnProfile || actionLoading}
className={`flex items-center space-x-2 px-4 py-2 rounded-md transition-colors ${
user.role === 'admin'
? 'bg-orange-100 text-orange-700 hover:bg-orange-200'
: 'bg-violet-100 text-violet-700 hover:bg-violet-200'
} disabled:opacity-50 disabled:cursor-not-allowed`}
>
{user.role === 'admin' ? (
<>
<ShieldOff className="w-4 h-4" />
<span>Demote to User</span>
</>
) : (
<>
<Shield className="w-4 h-4" />
<span>Promote to Admin</span>
</>
)}
</button>
{isOwnProfile && (
<div className="absolute bottom-full left-0 mb-2 px-3 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
You cannot demote yourself
</div>
)}
</div>
</div>
</div>
{/* Recent Activity */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-lg font-semibold mb-4 flex items-center">
<Activity className="w-5 h-5 mr-2" />
Recent Activity
</h2>
{recentActivity.length === 0 ? (
<div className="text-center py-8 text-gray-500">
<Clock className="w-12 h-12 mx-auto mb-3 text-gray-300" />
<p>No recent activity recorded</p>
</div>
) : (
<div className="space-y-3">
{recentActivity.map((activity, index) => (
<div
key={activity._id || index}
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
>
<div>
<p className="font-medium text-gray-900">
{getActivityDescription(activity)}
</p>
{activity.metadata?.ip && (
<p className="text-sm text-gray-500">
IP: {activity.metadata.ip}
</p>
)}
</div>
<span className="text-sm text-gray-500">
{formatDateTime(activity.timestamp)}
</span>
</div>
))}
</div>
)}
</div>
{/* Status Confirmation Dialog */}
{showStatusConfirm && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
<div className="bg-white rounded-lg max-w-md w-full p-6">
<h3 className="text-lg font-semibold mb-4">
{user.isActive ? 'Disable User' : 'Enable User'}
</h3>
<p className="text-gray-600 mb-6">
{user.isActive
? `Are you sure you want to disable ${user.name}? They will no longer be able to access the application.`
: `Are you sure you want to enable ${user.name}? They will be able to access the application again.`}
</p>
<div className="flex justify-end space-x-3">
<button
onClick={() => setShowStatusConfirm(false)}
disabled={actionLoading}
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
>
Cancel
</button>
<button
onClick={handleToggleStatus}
disabled={actionLoading}
className={`px-4 py-2 rounded-md text-white disabled:opacity-50 ${
user.isActive
? 'bg-red-600 hover:bg-red-700'
: 'bg-green-600 hover:bg-green-700'
}`}
>
{actionLoading ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : user.isActive ? (
'Disable'
) : (
'Enable'
)}
</button>
</div>
</div>
</div>
)}
{/* Role Confirmation Dialog */}
{showRoleConfirm && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
<div className="bg-white rounded-lg max-w-md w-full p-6">
<h3 className="text-lg font-semibold mb-4">
{user.role === 'admin' ? 'Demote User' : 'Promote User'}
</h3>
<p className="text-gray-600 mb-6">
{user.role === 'admin'
? `Are you sure you want to demote ${user.name} from admin? They will lose access to admin features.`
: `Are you sure you want to promote ${user.name} to admin? They will have full administrative access.`}
</p>
<div className="flex justify-end space-x-3">
<button
onClick={() => setShowRoleConfirm(false)}
disabled={actionLoading}
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
>
Cancel
</button>
<button
onClick={handleToggleRole}
disabled={actionLoading}
className={`px-4 py-2 rounded-md text-white disabled:opacity-50 ${
user.role === 'admin'
? 'bg-orange-600 hover:bg-orange-700'
: 'bg-violet-600 hover:bg-violet-700'
}`}
>
{actionLoading ? (
<RefreshCw className="w-4 h-4 animate-spin" />
) : user.role === 'admin' ? (
'Demote'
) : (
'Promote'
)}
</button>
</div>
</div>
</div>
)}
</div>
);
};
export default UserDetail;

View File

@ -0,0 +1,382 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, ChevronLeft, ChevronRight, Users, RefreshCw } from 'lucide-react';
const API_BASE = 'https://apartments.maverickapplications.com/api';
const UserList = () => {
const navigate = useNavigate();
// State
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// Pagination
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [totalUsers, setTotalUsers] = useState(0);
const limit = 20;
// Filters
const [searchQuery, setSearchQuery] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [statusFilter, setStatusFilter] = useState('all');
const [sortBy, setSortBy] = useState('createdAt');
const [sortOrder, setSortOrder] = useState('desc');
// Debounce search input (300ms)
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedSearch(searchQuery);
setPage(1); // Reset to first page on search
}, 300);
return () => clearTimeout(timer);
}, [searchQuery]);
// Fetch users
const fetchUsers = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
sortBy,
sortOrder
});
if (debouncedSearch) {
params.append('search', debouncedSearch);
}
if (statusFilter !== 'all') {
params.append('status', statusFilter);
}
const response = await fetch(`${API_BASE}/admin/users?${params}`, {
credentials: 'include'
});
if (!response.ok) {
throw new Error('Failed to fetch users');
}
const data = await response.json();
setUsers(data.data.users);
setTotalPages(data.data.pagination.totalPages);
setTotalUsers(data.data.pagination.total);
} catch (err) {
console.error('Error fetching users:', err);
setError(err.message);
} finally {
setLoading(false);
}
}, [page, debouncedSearch, statusFilter, sortBy, sortOrder]);
// Fetch on mount and when dependencies change
useEffect(() => {
fetchUsers();
}, [fetchUsers]);
// Handle row click
const handleRowClick = (userId) => {
navigate(`/admin/users/${userId}`);
};
// Handle status filter change
const handleStatusChange = (e) => {
setStatusFilter(e.target.value);
setPage(1);
};
// Handle sort change
const handleSortChange = (field) => {
if (sortBy === field) {
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
} else {
setSortBy(field);
setSortOrder('desc');
}
setPage(1);
};
// Format date helper
const formatDate = (dateStr) => {
if (!dateStr) return 'Never';
return new Date(dateStr).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
};
// Format datetime helper
const formatDateTime = (dateStr) => {
if (!dateStr) return 'Never';
return new Date(dateStr).toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
// Sort indicator
const SortIndicator = ({ field }) => {
if (sortBy !== field) return null;
return (
<span className="ml-1">
{sortOrder === 'asc' ? '\u2191' : '\u2193'}
</span>
);
};
if (error) {
return (
<div className="min-h-screen bg-gray-50 p-6">
<div className="max-w-7xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
<p className="text-red-700 mb-4">Error: {error}</p>
<button
onClick={fetchUsers}
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
>
Try Again
</button>
</div>
</div>
</div>
);
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900">User Management</h1>
<p className="text-gray-600">
{totalUsers} total user{totalUsers !== 1 ? 's' : ''}
</p>
</div>
<button
onClick={fetchUsers}
disabled={loading}
className="flex items-center space-x-2 px-4 py-2 bg-violet-600 text-white rounded-md hover:bg-violet-700 disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</button>
</div>
{/* Filters */}
<div className="bg-white rounded-lg shadow-md p-4">
<div className="flex flex-wrap items-center gap-4">
{/* Search */}
<div className="flex-1 min-w-[250px]">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="Search by name or email..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
/>
</div>
</div>
{/* Status Filter */}
<div className="flex items-center space-x-2">
<label className="text-sm font-medium text-gray-700">Status:</label>
<select
value={statusFilter}
onChange={handleStatusChange}
className="border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-violet-500 focus:border-violet-500"
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="disabled">Disabled</option>
</select>
</div>
</div>
</div>
{/* Users Table */}
<div className="bg-white rounded-lg shadow-md overflow-hidden">
{loading && users.length === 0 ? (
<div className="flex items-center justify-center py-12">
<RefreshCw className="w-8 h-8 animate-spin text-violet-600" />
<span className="ml-3 text-gray-600">Loading users...</span>
</div>
) : users.length === 0 ? (
<div className="text-center py-12">
<Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-gray-900 mb-2">No Users Found</h3>
<p className="text-gray-600">
{debouncedSearch || statusFilter !== 'all'
? 'Try adjusting your filters to see more results.'
: 'No users have signed up yet.'}
</p>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full min-w-max">
<thead className="bg-gray-50 border-b">
<tr>
<th className="text-left py-3 px-4 font-semibold text-gray-700">User</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">Email</th>
<th
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
onClick={() => handleSortChange('role')}
>
Role
<SortIndicator field="role" />
</th>
<th
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
onClick={() => handleSortChange('isActive')}
>
Status
<SortIndicator field="isActive" />
</th>
<th
className="text-center py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
onClick={() => handleSortChange('loginCount')}
>
Logins
<SortIndicator field="loginCount" />
</th>
<th
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
onClick={() => handleSortChange('lastLoginAt')}
>
Last Login
<SortIndicator field="lastLoginAt" />
</th>
<th
className="text-left py-3 px-4 font-semibold text-gray-700 cursor-pointer hover:bg-gray-100"
onClick={() => handleSortChange('createdAt')}
>
Created
<SortIndicator field="createdAt" />
</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr
key={user._id}
onClick={() => handleRowClick(user._id)}
className={`border-b cursor-pointer transition-colors ${
index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
} hover:bg-violet-50`}
>
{/* Avatar + Name */}
<td className="py-3 px-4">
<div className="flex items-center space-x-3">
{user.picture ? (
<img
src={user.picture}
alt={user.name}
className="w-8 h-8 rounded-full"
/>
) : (
<div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center">
<span className="text-sm font-medium text-gray-600">
{user.name?.charAt(0)?.toUpperCase() || '?'}
</span>
</div>
)}
<span className="font-medium text-gray-900">{user.name}</span>
</div>
</td>
{/* Email */}
<td className="py-3 px-4 text-gray-600">{user.email}</td>
{/* Role */}
<td className="py-3 px-4 text-center">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
user.role === 'admin'
? 'bg-violet-100 text-violet-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{user.role}
</span>
</td>
{/* Status */}
<td className="py-3 px-4 text-center">
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
user.isActive
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}
>
{user.isActive ? 'Active' : 'Disabled'}
</span>
</td>
{/* Login Count */}
<td className="py-3 px-4 text-center text-gray-600">
{user.loginCount || 0}
</td>
{/* Last Login */}
<td className="py-3 px-4 text-gray-600">
{formatDateTime(user.lastLoginAt)}
</td>
{/* Created */}
<td className="py-3 px-4 text-gray-600">
{formatDate(user.createdAt)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-t">
<div className="text-sm text-gray-600">
Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, totalUsers)} of {totalUsers} users
</div>
<div className="flex items-center space-x-2">
<button
onClick={() => setPage(Math.max(1, page - 1))}
disabled={page === 1 || loading}
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
<ChevronLeft className="w-4 h-4" />
<span className="ml-1">Previous</span>
</button>
<span className="px-3 py-1 text-sm">
Page {page} of {totalPages}
</span>
<button
onClick={() => setPage(Math.min(totalPages, page + 1))}
disabled={page === totalPages || loading}
className="flex items-center px-3 py-1 border border-gray-300 rounded-md bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
<span className="mr-1">Next</span>
<ChevronRight className="w-4 h-4" />
</button>
</div>
</div>
)}
</div>
</div>
);
};
export default UserList;