import React, { useState, useEffect } from 'react'; const UserManagement = ({ showToast, token }) => { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(''); const [selectedUser, setSelectedUser] = useState(null); const fetchUsers = async () => { setLoading(true); try { const res = await fetch(`/api/users`, { headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) { const data = await res.json(); setUsers(data); } else { showToast('Failed to fetch user directory.', 'danger'); } } catch (e) { console.error(e); showToast('Network error loading user directory.', 'danger'); } finally { setLoading(false); } }; useEffect(() => { fetchUsers(); }, []); const toggleStatus = async (userId, userName) => { try { const res = await fetch(`/api/users/${userId}/toggle-status`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } }); const data = await res.json(); if (res.ok) { showToast(`User ${userName} status updated to ${data.status}.`, data.status === 'Active' ? 'success' : 'danger'); fetchUsers(); } else { showToast(data.error || 'Failed to update user status.', 'danger'); } } catch (e) { console.error(e); showToast('Network error updating user status.', 'danger'); } }; const forgivePenalty = async (userId, userName) => { if (!window.confirm(`Are you sure you want to forgive penalty points for ${userName}?`)) return; try { const res = await fetch(`/api/users/${userId}/reset-penalty`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) { showToast(`Penalty points forgiven for ${userName}.`, 'success'); fetchUsers(); } else { const data = await res.json(); showToast(data.error || 'Failed to forgive penalty.', 'danger'); } } catch (e) { showToast('Network error forgiving penalty.', 'danger'); } }; const promoteToAdmin = async (userId, userName) => { if (!window.confirm(`Are you sure you want to promote ${userName} to Admin?`)) return; try { const res = await fetch(`/api/users/${userId}/assign-admin`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } }); const data = await res.json(); if (res.ok) { showToast(`User ${userName} successfully promoted to Admin.`, 'success'); fetchUsers(); } else { showToast(data.error || 'Failed to promote user.', 'danger'); } } catch (e) { console.error(e); showToast('Network error promoting user.', 'danger'); } }; const handleExportData = () => { try { const headers = ['Employee ID', 'Name', 'Email', 'Gender', 'Role', 'Status', 'Joined Date', 'Vehicle No', 'Make', 'Model', 'Capacity']; const rows = users.map(u => [ `EMP-${u.id}`, u.name, u.email, u.gender || 'N/A', u.role, u.status, new Date(u.created_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' }), u.vehicle_no || 'N/A', u.vehicle_make || 'N/A', u.vehicle_model || 'N/A', u.vehicle_capacity || 'N/A' ]); const csvContent = "data:text/csv;charset=utf-8," + [headers.join(','), ...rows.map(r => r.join(','))].join('\n'); const encodedUri = encodeURI(csvContent); const link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", `reliance_carpool_users_${Date.now()}.csv`); document.body.appendChild(link); link.click(); document.body.removeChild(link); showToast(`Exported ${users.length} user records to CSV successfully!`, 'success'); } catch (e) { showToast('Failed to export CSV data.', 'danger'); } }; const filteredUsers = users.filter(u => u.name.toLowerCase().includes(searchTerm.toLowerCase()) || `EMP-${u.id}`.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase()) ); return (

User Directory

setSearchTerm(e.target.value)} className="glass-input rounded-lg px-4 py-2 text-white placeholder:text-on-surface-variant/30 outline-none text-body-sm focus:border-primary transition-all w-64" />
{loading ? (
Loading user records from database...
) : (
{filteredUsers.map(user => ( ))} {filteredUsers.length === 0 && ( )}
Employee ID Name Email Gender Role Joined Date Penalty Pts Status Actions
EMP-{user.id} {user.name} {user.email} {user.gender || 'N/A'} {user.role} {new Date(user.created_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })} = 2 ? 'text-error-red' : (user.penalty_points === 1 ? 'text-warning-orange' : 'text-on-surface-variant')}`}> {user.penalty_points || 0} {user.status || 'Active'}
{user.penalty_points > 0 && ( )} {user.role !== 'Admin' && ( )}
No live users found matching "{searchTerm}"
)} {/* Details Modal */} {selectedUser && (
setSelectedUser(null)}>
e.stopPropagation()}>

Employee Profile Details

{selectedUser.name.charAt(0)}

{selectedUser.name}

{selectedUser.status || 'Active'}
Employee ID
EMP-{selectedUser.id}
Corporate Email
{selectedUser.email}
Gender
{selectedUser.gender || 'N/A'}
Registered Role
{selectedUser.role}
Joined Date
{new Date(selectedUser.created_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })}
{selectedUser.role === 'Pool Host' && (
verified Vehicle Information
Vehicle Make/Model
{selectedUser.vehicle_make || 'N/A'} {selectedUser.vehicle_model || ''}
Registration No.
{selectedUser.vehicle_no || 'N/A'}
Capacity
{selectedUser.vehicle_capacity || 'N/A'}
Gate Pass Status
{selectedUser.has_vehicle_pass ? 'Valid Pass Assigned' : 'No Active Pass'}
)}
)}
); }; export default UserManagement;