import { useState, FormEvent } from 'react'; import { useGetUsers, useUpdateUser } from '../generated/anthoLumeAPIV1'; import type { User, UsersResponse } from '../generated/model'; import { AddIcon, DeleteIcon } from '../icons'; import { useToasts } from '../components/ToastContext'; import { getErrorMessage } from '../utils/errors'; export default function AdminUsersPage() { const { data: usersData, isLoading, refetch } = useGetUsers({}); const updateUser = useUpdateUser(); const { showInfo, showError } = useToasts(); const [showAddForm, setShowAddForm] = useState(false); const [newUsername, setNewUsername] = useState(''); const [newPassword, setNewPassword] = useState(''); const [newIsAdmin, setNewIsAdmin] = useState(false); const users = usersData?.status === 200 ? ((usersData.data as UsersResponse).users ?? []) : []; const handleCreateUser = (e: FormEvent) => { e.preventDefault(); if (!newUsername || !newPassword) return; updateUser.mutate( { data: { operation: 'CREATE', user: newUsername, password: newPassword, is_admin: newIsAdmin, }, }, { onSuccess: () => { showInfo('User created successfully'); setShowAddForm(false); setNewUsername(''); setNewPassword(''); setNewIsAdmin(false); refetch(); }, onError: error => { showError('Failed to create user: ' + getErrorMessage(error)); }, } ); }; const handleDeleteUser = (userId: string) => { updateUser.mutate( { data: { operation: 'DELETE', user: userId, }, }, { onSuccess: () => { showInfo('User deleted successfully'); refetch(); }, onError: error => { showError('Failed to delete user: ' + getErrorMessage(error)); }, } ); }; const handleUpdatePassword = (userId: string, password: string) => { if (!password) return; updateUser.mutate( { data: { operation: 'UPDATE', user: userId, password, }, }, { onSuccess: () => { showInfo('Password updated successfully'); refetch(); }, onError: error => { showError('Failed to update password: ' + getErrorMessage(error)); }, } ); }; const handleToggleAdmin = (userId: string, isAdmin: boolean) => { updateUser.mutate( { data: { operation: 'UPDATE', user: userId, is_admin: isAdmin, }, }, { onSuccess: () => { const role = isAdmin ? 'admin' : 'user'; showInfo(`User permissions updated to ${role}`); refetch(); }, onError: error => { showError('Failed to update admin status: ' + getErrorMessage(error)); }, } ); }; if (isLoading) { return
Loading...
; } return (
{showAddForm && (
setNewUsername(e.target.value)} placeholder="Username" className="bg-gray-300 p-2 text-black dark:bg-gray-700 dark:text-white" /> setNewPassword(e.target.value)} placeholder="Password" className="bg-gray-300 p-2 text-black dark:bg-gray-700 dark:text-white" />
setNewIsAdmin(e.target.checked)} />
)}
{users.length === 0 ? ( ) : ( users.map((user: User) => ( )) )}
User Password Permissions Created
No Results

{user.id}

{user.created_at}

); }