users-table.tsx445 lines, 13 KB
| 1 | "use client"; |
| 2 | |
| 3 | import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; |
| 4 | import { Badge } from "@/components/ui/badge"; |
| 5 | import { Button } from "@/components/ui/button"; |
| 6 | import { |
| 7 | DropdownMenu, |
| 8 | DropdownMenuContent, |
| 9 | DropdownMenuItem, |
| 10 | DropdownMenuLabel, |
| 11 | DropdownMenuSeparator, |
| 12 | DropdownMenuTrigger, |
| 13 | } from "@/components/ui/dropdown-menu"; |
| 14 | import { |
| 15 | Pagination, |
| 16 | PaginationContent, |
| 17 | PaginationEllipsis, |
| 18 | PaginationItem, |
| 19 | PaginationLink, |
| 20 | PaginationNext, |
| 21 | PaginationPrevious, |
| 22 | } from "@/components/ui/pagination"; |
| 23 | import { |
| 24 | Table, |
| 25 | TableBody, |
| 26 | TableCell, |
| 27 | TableHead, |
| 28 | TableHeader, |
| 29 | TableRow, |
| 30 | } from "@/components/ui/table"; |
| 31 | import { UserWithoutPassword } from "@/server/actions/admin/users/get-all-users"; |
| 32 | import { updateUserRole } from "@/server/actions/admin/users/update-user-role"; |
| 33 | import { formatDistanceToNow } from "date-fns"; |
| 34 | import { |
| 35 | ArrowDown, |
| 36 | ArrowUp, |
| 37 | ArrowUpDown, |
| 38 | Loader2, |
| 39 | MoreHorizontalIcon, |
| 40 | ShieldIcon, |
| 41 | User, |
| 42 | } from "lucide-react"; |
| 43 | import { useRouter } from "next/navigation"; |
| 44 | import { useState } from "react"; |
| 45 | import { toast } from "sonner"; |
| 46 | |
| 47 | interface UsersTableProps { |
| 48 | users: UserWithoutPassword[]; |
| 49 | total: number; |
| 50 | currentPage: number; |
| 51 | currentSearch: string; |
| 52 | currentSortBy: string; |
| 53 | currentSortOrder: string; |
| 54 | } |
| 55 | |
| 56 | export function UsersTable({ |
| 57 | users, |
| 58 | total, |
| 59 | currentPage, |
| 60 | currentSearch, |
| 61 | currentSortBy, |
| 62 | currentSortOrder, |
| 63 | }: UsersTableProps) { |
| 64 | const router = useRouter(); |
| 65 | const [isLoading, setIsLoading] = useState<string | null>(null); |
| 66 | |
| 67 | // Get the current path from window location or default to /admin/users |
| 68 | const basePath = |
| 69 | typeof window !== "undefined" ? window.location.pathname : "/admin/users"; |
| 70 | |
| 71 | // Extract any additional query parameters that should be preserved |
| 72 | const preserveParams = () => { |
| 73 | if (typeof window === "undefined") return ""; |
| 74 | |
| 75 | const url = new URL(window.location.href); |
| 76 | const params = new URLSearchParams(url.search); |
| 77 | let paramString = ""; |
| 78 | |
| 79 | // Preserve any additional parameters if needed |
| 80 | // For example, if you have a filter parameter: |
| 81 | // if (params.has("filter")) { |
| 82 | // paramString += `&filter=${params.get("filter")}`; |
| 83 | // } |
| 84 | |
| 85 | return paramString; |
| 86 | }; |
| 87 | |
| 88 | // Calculate pagination |
| 89 | const limit = 10; |
| 90 | const totalPages = Math.ceil(total / limit); |
| 91 | |
| 92 | // Handle sort change |
| 93 | const handleSort = (column: string) => { |
| 94 | const params = new URLSearchParams(); |
| 95 | |
| 96 | // Keep current search if any |
| 97 | if (currentSearch) { |
| 98 | params.set("search", currentSearch); |
| 99 | } |
| 100 | |
| 101 | // Set sort parameters |
| 102 | params.set("sortBy", column); |
| 103 | |
| 104 | // Toggle sort order if clicking the same column |
| 105 | if (currentSortBy === column) { |
| 106 | params.set("sortOrder", currentSortOrder === "asc" ? "desc" : "asc"); |
| 107 | } else { |
| 108 | params.set("sortOrder", "asc"); |
| 109 | } |
| 110 | |
| 111 | // Reset to page 1 when sorting |
| 112 | params.set("page", "1"); |
| 113 | |
| 114 | // Preserve any additional parameters |
| 115 | const additionalParams = preserveParams(); |
| 116 | if (additionalParams) { |
| 117 | const additionalParamsObj = new URLSearchParams( |
| 118 | additionalParams.substring(1) |
| 119 | ); // Remove the leading & |
| 120 | additionalParamsObj.forEach((value, key) => { |
| 121 | params.set(key, value); |
| 122 | }); |
| 123 | } |
| 124 | |
| 125 | // Navigate with updated params |
| 126 | router.push(`${basePath}?${params.toString()}`); |
| 127 | }; |
| 128 | |
| 129 | // Generate pagination links |
| 130 | const getPaginationItems = () => { |
| 131 | const items = []; |
| 132 | const additionalParams = preserveParams(); |
| 133 | |
| 134 | // Always show first page |
| 135 | items.push( |
| 136 | <PaginationItem key="first"> |
| 137 | <PaginationLink |
| 138 | href={`${basePath}?page=1${ |
| 139 | currentSearch ? `&search=${currentSearch}` : "" |
| 140 | }${ |
| 141 | currentSortBy |
| 142 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 143 | : "" |
| 144 | }${additionalParams}`} |
| 145 | isActive={currentPage === 1} |
| 146 | > |
| 147 | 1 |
| 148 | </PaginationLink> |
| 149 | </PaginationItem> |
| 150 | ); |
| 151 | |
| 152 | // Show ellipsis if needed |
| 153 | if (currentPage > 3) { |
| 154 | items.push( |
| 155 | <PaginationItem key="ellipsis-1"> |
| 156 | <PaginationEllipsis /> |
| 157 | </PaginationItem> |
| 158 | ); |
| 159 | } |
| 160 | |
| 161 | // Show current page and surrounding pages |
| 162 | for ( |
| 163 | let i = Math.max(2, currentPage - 1); |
| 164 | i <= Math.min(totalPages - 1, currentPage + 1); |
| 165 | i++ |
| 166 | ) { |
| 167 | if (i === 1 || i === totalPages) continue; // Skip first and last page as they're always shown |
| 168 | |
| 169 | items.push( |
| 170 | <PaginationItem key={i}> |
| 171 | <PaginationLink |
| 172 | href={`${basePath}?page=${i}${ |
| 173 | currentSearch ? `&search=${currentSearch}` : "" |
| 174 | }${ |
| 175 | currentSortBy |
| 176 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 177 | : "" |
| 178 | }${additionalParams}`} |
| 179 | isActive={currentPage === i} |
| 180 | > |
| 181 | {i} |
| 182 | </PaginationLink> |
| 183 | </PaginationItem> |
| 184 | ); |
| 185 | } |
| 186 | |
| 187 | // Show ellipsis if needed |
| 188 | if (currentPage < totalPages - 2) { |
| 189 | items.push( |
| 190 | <PaginationItem key="ellipsis-2"> |
| 191 | <PaginationEllipsis /> |
| 192 | </PaginationItem> |
| 193 | ); |
| 194 | } |
| 195 | |
| 196 | // Always show last page if there's more than one page |
| 197 | if (totalPages > 1) { |
| 198 | items.push( |
| 199 | <PaginationItem key="last"> |
| 200 | <PaginationLink |
| 201 | href={`${basePath}?page=${totalPages}${ |
| 202 | currentSearch ? `&search=${currentSearch}` : "" |
| 203 | }${ |
| 204 | currentSortBy |
| 205 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 206 | : "" |
| 207 | }${additionalParams}`} |
| 208 | isActive={currentPage === totalPages} |
| 209 | > |
| 210 | {totalPages} |
| 211 | </PaginationLink> |
| 212 | </PaginationItem> |
| 213 | ); |
| 214 | } |
| 215 | |
| 216 | return items; |
| 217 | }; |
| 218 | |
| 219 | const getSortIcon = (column: string) => { |
| 220 | if (currentSortBy !== column) { |
| 221 | return <ArrowUpDown className="ml-2 size-4" />; |
| 222 | } |
| 223 | |
| 224 | return currentSortOrder === "asc" ? ( |
| 225 | <ArrowUp className="ml-2 size-4" /> |
| 226 | ) : ( |
| 227 | <ArrowDown className="ml-2 size-4" /> |
| 228 | ); |
| 229 | }; |
| 230 | |
| 231 | const getUserInitials = (name: string | null) => { |
| 232 | if (!name) return "U"; |
| 233 | |
| 234 | const parts = name.split(" "); |
| 235 | if (parts.length === 1) return parts[0].charAt(0).toUpperCase(); |
| 236 | |
| 237 | return ( |
| 238 | parts[0].charAt(0).toUpperCase() + |
| 239 | parts[parts.length - 1].charAt(0).toUpperCase() |
| 240 | ); |
| 241 | }; |
| 242 | |
| 243 | const handleRoleToggle = async (userId: string, currentRole: string) => { |
| 244 | try { |
| 245 | setIsLoading(userId); |
| 246 | |
| 247 | const newRole = currentRole === "admin" ? "user" : "admin"; |
| 248 | const response = await updateUserRole(userId, newRole); |
| 249 | |
| 250 | if (response.success) { |
| 251 | toast.success("User role updated successfully", { |
| 252 | description: `User role has been updated to ${newRole}`, |
| 253 | }); |
| 254 | |
| 255 | router.refresh(); |
| 256 | } else { |
| 257 | toast.error("Failed to update user role", { |
| 258 | description: response.error || "An error occurred", |
| 259 | }); |
| 260 | } |
| 261 | } catch (error) { |
| 262 | console.error("Error updating user role:", error); |
| 263 | toast.error("Failed to update user role", { |
| 264 | description: "An error occurred", |
| 265 | }); |
| 266 | } finally { |
| 267 | setIsLoading(null); |
| 268 | } |
| 269 | }; |
| 270 | |
| 271 | return ( |
| 272 | <div className="space-y-4"> |
| 273 | <div className="rounded-md border"> |
| 274 | <Table> |
| 275 | <TableHeader> |
| 276 | <TableRow> |
| 277 | <TableHead className="w-[250px]"> |
| 278 | <button |
| 279 | onClick={() => handleSort("name")} |
| 280 | className="flex items-center font-medium" |
| 281 | > |
| 282 | User |
| 283 | {getSortIcon("name")} |
| 284 | </button> |
| 285 | </TableHead> |
| 286 | <TableHead> |
| 287 | <button |
| 288 | onClick={() => handleSort("email")} |
| 289 | className="flex items-center font-medium" |
| 290 | > |
| 291 | |
| 292 | {getSortIcon("email")} |
| 293 | </button> |
| 294 | </TableHead> |
| 295 | <TableHead className="w-[120px]"> |
| 296 | <button |
| 297 | onClick={() => handleSort("role")} |
| 298 | className="flex items-center font-medium" |
| 299 | > |
| 300 | Role |
| 301 | {getSortIcon("role")} |
| 302 | </button> |
| 303 | </TableHead> |
| 304 | <TableHead className="w-[150px]"> |
| 305 | <button |
| 306 | onClick={() => handleSort("createdAt")} |
| 307 | className="flex items-center font-medium" |
| 308 | > |
| 309 | Joined |
| 310 | {getSortIcon("createdAt")} |
| 311 | </button> |
| 312 | </TableHead> |
| 313 | <TableHead className="w-[80px]">Actions</TableHead> |
| 314 | </TableRow> |
| 315 | </TableHeader> |
| 316 | <TableBody> |
| 317 | {users.length === 0 ? ( |
| 318 | <TableRow> |
| 319 | <TableCell colSpan={5} className="h-24 text-center"> |
| 320 | {currentSearch |
| 321 | ? "No users found with the given search criteria" |
| 322 | : "No users found"} |
| 323 | </TableCell> |
| 324 | </TableRow> |
| 325 | ) : ( |
| 326 | users.map((user) => ( |
| 327 | <TableRow key={user.id}> |
| 328 | <TableCell className="font-medium"> |
| 329 | <div className="flex items-center gap-3"> |
| 330 | <Avatar> |
| 331 | <AvatarImage |
| 332 | src={user.image || undefined} |
| 333 | alt={user.name || "User"} |
| 334 | /> |
| 335 | <AvatarFallback> |
| 336 | {getUserInitials(user.name)} |
| 337 | </AvatarFallback> |
| 338 | </Avatar> |
| 339 | <div> |
| 340 | <div className="font-medium"> |
| 341 | {user.name || "Unknown User"} |
| 342 | </div> |
| 343 | <div className="text-xs text-muted-foreground"> |
| 344 | ID: {user.id.substring(0, 8)}... |
| 345 | </div> |
| 346 | </div> |
| 347 | </div> |
| 348 | </TableCell> |
| 349 | <TableCell>{user.email}</TableCell> |
| 350 | <TableCell> |
| 351 | <Badge |
| 352 | variant={ |
| 353 | user.role === "admin" ? "destructive" : "secondary" |
| 354 | } |
| 355 | className="flex w-fit items-center gap-1" |
| 356 | > |
| 357 | {user.role === "admin" ? <ShieldIcon /> : <User />} |
| 358 | {user.role} |
| 359 | </Badge> |
| 360 | </TableCell> |
| 361 | <TableCell> |
| 362 | {formatDistanceToNow(new Date(user.createdAt), { |
| 363 | addSuffix: true, |
| 364 | })} |
| 365 | </TableCell> |
| 366 | <TableCell className="text-right"> |
| 367 | <DropdownMenu> |
| 368 | <DropdownMenuTrigger asChild> |
| 369 | <Button |
| 370 | variant={"ghost"} |
| 371 | size={"icon"} |
| 372 | disabled={isLoading === user.id} |
| 373 | > |
| 374 | {isLoading === user.id ? ( |
| 375 | <Loader2 className="size-4 animate-spin" /> |
| 376 | ) : ( |
| 377 | <MoreHorizontalIcon /> |
| 378 | )} |
| 379 | </Button> |
| 380 | </DropdownMenuTrigger> |
| 381 | <DropdownMenuContent align="end"> |
| 382 | <DropdownMenuLabel>Actions</DropdownMenuLabel> |
| 383 | <DropdownMenuSeparator /> |
| 384 | <DropdownMenuItem |
| 385 | className={ |
| 386 | user.role === "admin" |
| 387 | ? "text-destructive" |
| 388 | : "text-blue-600" |
| 389 | } |
| 390 | onClick={() => handleRoleToggle(user.id, user.role)} |
| 391 | disabled={isLoading === user.id} |
| 392 | > |
| 393 | {user.role === "admin" ? "Demote" : "Promote"} to{" "} |
| 394 | {user.role === "admin" ? "User" : "Admin"} |
| 395 | </DropdownMenuItem> |
| 396 | </DropdownMenuContent> |
| 397 | </DropdownMenu> |
| 398 | </TableCell> |
| 399 | </TableRow> |
| 400 | )) |
| 401 | )} |
| 402 | </TableBody> |
| 403 | </Table> |
| 404 | </div> |
| 405 | |
| 406 | {totalPages > 1 && ( |
| 407 | <Pagination> |
| 408 | <PaginationContent> |
| 409 | <PaginationItem> |
| 410 | <PaginationPrevious |
| 411 | href={`${basePath}?page=${Math.max(1, currentPage - 1)}${ |
| 412 | currentSearch ? `&search=${currentSearch}` : "" |
| 413 | }${ |
| 414 | currentSortBy |
| 415 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 416 | : "" |
| 417 | }${preserveParams()}`} |
| 418 | /> |
| 419 | </PaginationItem> |
| 420 | |
| 421 | {getPaginationItems()} |
| 422 | |
| 423 | <PaginationItem> |
| 424 | <PaginationNext |
| 425 | href={`${basePath}?page=${Math.min( |
| 426 | totalPages, |
| 427 | currentPage + 1 |
| 428 | )}${currentSearch ? `&search=${currentSearch}` : ""}${ |
| 429 | currentSortBy |
| 430 | ? `&sortBy=${currentSortBy}&sortOrder=${currentSortOrder}` |
| 431 | : "" |
| 432 | }${preserveParams()}`} |
| 433 | /> |
| 434 | </PaginationItem> |
| 435 | </PaginationContent> |
| 436 | </Pagination> |
| 437 | )} |
| 438 | |
| 439 | <div className="text-xs text-muted-foreground"> |
| 440 | Showing {users.length} of {total} users |
| 441 | {currentSearch && ` matching "${currentSearch}"`} |
| 442 | </div> |
| 443 | </div> |
| 444 | ); |
| 445 | } |