"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Plus, Loader2, Shield, Pencil, Trash2 } from "lucide-react"; import { toast } from "sonner"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; interface Role { id: string; name: string; description: string | null; permissions: Record; is_system: boolean; user_count: string; created_at: string; } export function RoleTable() { const router = useRouter(); const [roles, setRoles] = useState([]); const [isLoading, setIsLoading] = useState(true); const [deleteRoleId, setDeleteRoleId] = useState(null); const [isDeleting, setIsDeleting] = useState(false); async function fetchRoles() { setIsLoading(true); try { const response = await fetch("/api/admin/roles"); if (!response.ok) throw new Error("Failed to fetch roles"); const data = await response.json(); setRoles(data.roles); } catch (error) { console.error("Error fetching roles:", error); toast.error("Failed to load roles"); } finally { setIsLoading(false); } } useEffect(() => { fetchRoles(); }, []); async function handleDelete() { if (!deleteRoleId) return; setIsDeleting(true); try { const response = await fetch(`/api/admin/roles/${deleteRoleId}`, { method: "DELETE", }); if (!response.ok) { const data = await response.json(); throw new Error(data.error || "Failed to delete role"); } toast.success("Role deleted"); fetchRoles(); } catch (error) { toast.error(error instanceof Error ? error.message : "An error occurred"); } finally { setIsDeleting(false); setDeleteRoleId(null); } } function countPermissions(permissions: Record): number { return Object.values(permissions).reduce( (total, actions) => total + actions.length, 0 ); } return (
Name Description Permissions Users {isLoading ? ( ) : roles.length === 0 ? ( No roles found ) : ( roles.map((role) => (
{role.name} {role.is_system && ( System )}
{role.description || "-"} {countPermissions(role.permissions)} permissions {role.user_count} users
{!role.is_system && ( )}
)) )}
setDeleteRoleId(null)}> Delete Role Are you sure you want to delete this role? This action cannot be undone. Cancel {isDeleting ? ( <> Deleting... ) : ( "Delete" )}
); }