import { useEffect, useState, useCallback, useMemo } from "react" import { Bell, BellOff, AlertTriangle, Info, AlertCircle, CheckCircle2, ChevronLeft, ChevronRight, Megaphone, UserPlus, CreditCard, BookOpen, Video, ShieldAlert, MailOpen, Mail, CheckCheck, MailX, Search, ChevronDown, Calendar, Clock3, } from "lucide-react" import { Card, CardContent } from "../../components/ui/card" import { Badge } from "../../components/ui/badge" import { Button } from "../../components/ui/button" import { Input } from "../../components/ui/input" import { Textarea } from "../../components/ui/textarea" import { Select } from "../../components/ui/select" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "../../components/ui/dialog" import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "../../components/ui/dropdown-menu" import { FileUpload } from "../../components/ui/file-upload" import { cn } from "../../lib/utils" import { SpinnerIcon } from "../../components/ui/spinner-icon" import { useNavigate } from "react-router-dom" import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead, markAllUnread, sendBulkSms, sendBulkEmail, sendBulkPush, } from "../../api/notifications.api" import { getRoles } from "../../api/rbac.api" import { getTeamMembers } from "../../api/team.api" import { getUsers } from "../../api/users.api" import { getNotificationMessage, getNotificationTitle, type Notification } from "../../types/notification.types" import type { Role } from "../../types/rbac.types" import type { TeamMember } from "../../types/team.types" import type { UserApiDTO } from "../../types/user.types" import { toast } from "sonner" const PAGE_SIZE = 10 const TYPE_CONFIG: Record = { announcement: { icon: Megaphone, color: "text-brand-600", bg: "bg-brand-100" }, system_alert: { icon: ShieldAlert, color: "text-amber-600", bg: "bg-amber-50" }, issue_created: { icon: AlertCircle, color: "text-red-500", bg: "bg-red-50" }, issue_status_updated: { icon: CheckCircle2, color: "text-sky-600", bg: "bg-sky-50" }, course_created: { icon: BookOpen, color: "text-indigo-600", bg: "bg-indigo-50" }, course_enrolled: { icon: BookOpen, color: "text-teal-600", bg: "bg-teal-50" }, sub_course_created: { icon: BookOpen, color: "text-violet-600", bg: "bg-violet-50" }, video_added: { icon: Video, color: "text-pink-600", bg: "bg-pink-50" }, user_deleted: { icon: UserPlus, color: "text-red-600", bg: "bg-red-50" }, admin_created: { icon: UserPlus, color: "text-brand-600", bg: "bg-brand-100" }, team_member_created: { icon: UserPlus, color: "text-emerald-600", bg: "bg-emerald-50" }, subscription_activated: { icon: CreditCard, color: "text-green-600", bg: "bg-green-50" }, payment_verified: { icon: CreditCard, color: "text-green-600", bg: "bg-green-50" }, knowledge_level_update: { icon: Info, color: "text-sky-600", bg: "bg-sky-50" }, assessment_assigned: { icon: BookOpen, color: "text-orange-600", bg: "bg-orange-50" }, } const DEFAULT_TYPE_CONFIG = { icon: Bell, color: "text-grayScale-500", bg: "bg-grayScale-100" } function getLevelBadge(level: string) { switch (level) { case "error": case "critical": return "destructive" as const case "warning": return "warning" as const case "success": return "success" as const case "info": default: return "info" as const } } function formatTimestamp(ts: string) { const date = new Date(ts) const now = new Date() const diffMs = now.getTime() - date.getTime() const diffMin = Math.floor(diffMs / 60_000) const diffHr = Math.floor(diffMs / 3_600_000) const diffDay = Math.floor(diffMs / 86_400_000) if (diffMin < 1) return "Just now" if (diffMin < 60) return `${diffMin}m ago` if (diffHr < 24) return `${diffHr}h ago` if (diffDay < 7) return `${diffDay}d ago` return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: date.getFullYear() !== now.getFullYear() ? "numeric" : undefined, }) } function formatTypeLabel(type: string) { return type .split("_") .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) .join(" ") } function digitsOnly(value: string, maxLength: number) { return value.replace(/\D/g, "").slice(0, maxLength) } function NotificationItem({ notification, onToggleRead, toggling, }: { notification: Notification onToggleRead: (id: string, currentlyRead: boolean) => void toggling: boolean }) { const config = TYPE_CONFIG[notification.type] ?? DEFAULT_TYPE_CONFIG const Icon = config.icon return (
{/* Unread dot */} {!notification.is_read && ( )} {/* Icon */}
{/* Content */}
{getNotificationTitle(notification)} {notification.level}

{getNotificationMessage(notification)}

{formatTimestamp(notification.timestamp)}
{/* Meta row */}
{formatTypeLabel(notification.type)} {notification.delivery_channel} {notification.delivery_status !== "delivered" && notification.delivery_status !== "pending" && ( {notification.delivery_status} )} {notification.payload.tags && notification.payload.tags.length > 0 && ( notification.payload.tags.map((tag) => ( {tag} )) )}
) } export function NotificationsPage() { const navigate = useNavigate() const [notifications, setNotifications] = useState([]) const [totalCount, setTotalCount] = useState(0) const [globalUnread, setGlobalUnread] = useState(0) const [offset, setOffset] = useState(0) const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const [togglingIds, setTogglingIds] = useState>(new Set()) const [bulkLoading, setBulkLoading] = useState(false) const [selectedNotification, setSelectedNotification] = useState(null) const [detailOpen, setDetailOpen] = useState(false) const [channelFilter, setChannelFilter] = useState<"all" | "push" | "sms">("all") const [activeStatusTab, setActiveStatusTab] = useState<"all" | "read" | "unread">("all") const [searchTerm, setSearchTerm] = useState("") const [typeFilter, setTypeFilter] = useState<"all" | string>("all") const [levelFilter, setLevelFilter] = useState<"all" | string>("all") const [bulkOpen, setBulkOpen] = useState(false) const [bulkChannel, setBulkChannel] = useState<"sms" | "email" | "push">("sms") const [bulkTitle, setBulkTitle] = useState("") const [bulkMessage, setBulkMessage] = useState("") const [bulkRole, setBulkRole] = useState("") const [bulkUserIds, setBulkUserIds] = useState([]) const [bulkScheduledAt, setBulkScheduledAt] = useState("") const [bulkFile, setBulkFile] = useState(null) const [bulkSending, setBulkSending] = useState(false) const [bulkRoles, setBulkRoles] = useState([]) const [bulkUsers, setBulkUsers] = useState([]) const [bulkRolesLoading, setBulkRolesLoading] = useState(false) const [bulkUsersLoading, setBulkUsersLoading] = useState(false) const [scheduleMenuOpen, setScheduleMenuOpen] = useState(false) const [scheduleYear, setScheduleYear] = useState("") const [scheduleMonth, setScheduleMonth] = useState("") const [scheduleDay, setScheduleDay] = useState("") const [scheduleHour, setScheduleHour] = useState("") const [scheduleMinute, setScheduleMinute] = useState("") const filteredBulkUsers = useMemo(() => { if (!bulkRole.trim()) return bulkUsers const selectedRole = bulkRole.trim().toLowerCase() return bulkUsers.filter((user) => user.role?.toLowerCase() === selectedRole) }, [bulkUsers, bulkRole]) const scheduledAtLabel = useMemo(() => { if (!bulkScheduledAt) return "Set date & time" const parsed = new Date(bulkScheduledAt) if (Number.isNaN(parsed.getTime())) return bulkScheduledAt return parsed.toLocaleString("en-US", { month: "short", day: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit", }) }, [bulkScheduledAt]) const loadBulkOptions = useCallback(async () => { if (!bulkOpen) return const needsRoles = bulkRoles.length === 0 const needsUsers = bulkUsers.length === 0 if (!needsRoles && !needsUsers) return try { if (needsRoles) setBulkRolesLoading(true) if (needsUsers) setBulkUsersLoading(true) const tasks: Promise[] = [] if (needsRoles) { tasks.push( getRoles({ page: 1, page_size: 20 }) .then(async (res) => { const firstBatch = res.data?.data?.roles ?? [] const total = res.data?.data?.total ?? firstBatch.length const pageSize = 20 const totalPages = Math.max(1, Math.ceil(total / pageSize)) if (totalPages <= 1) { setBulkRoles(firstBatch) return } const remainingRequests: Array> = [] for (let page = 2; page <= totalPages; page += 1) { remainingRequests.push(getRoles({ page, page_size: pageSize })) } try { const responses = await Promise.all(remainingRequests) const rest = responses.flatMap((r) => r.data?.data?.roles ?? []) setBulkRoles([...firstBatch, ...rest]) } catch { setBulkRoles(firstBatch) } }) .catch(() => { setBulkRoles([]) }), ) } if (needsUsers) { tasks.push( getUsers(1, 20) .then(async (res) => { const firstBatch = res.data?.data?.users ?? [] const total = res.data?.data?.total ?? firstBatch.length const pageSize = 20 const totalPages = Math.max(1, Math.ceil(total / pageSize)) if (totalPages <= 1) { setBulkUsers(firstBatch) return } const remainingRequests: Array> = [] for (let page = 2; page <= totalPages; page += 1) { remainingRequests.push(getUsers(page, pageSize)) } try { const responses = await Promise.all(remainingRequests) const rest = responses.flatMap((r) => r.data?.data?.users ?? []) setBulkUsers([...firstBatch, ...rest]) } catch { setBulkUsers(firstBatch) } }) .catch(() => { setBulkUsers([]) }), ) } await Promise.all(tasks) } finally { setBulkRolesLoading(false) setBulkUsersLoading(false) } }, [bulkOpen, bulkRoles.length, bulkUsers.length]) useEffect(() => { loadBulkOptions() }, [loadBulkOptions]) useEffect(() => { if (!scheduleMenuOpen) return if (!bulkScheduledAt) { setScheduleYear("") setScheduleMonth("") setScheduleDay("") setScheduleHour("") setScheduleMinute("") return } const [datePart = "", timePart = ""] = bulkScheduledAt.split("T") const [y = "", m = "", d = ""] = datePart.split("-") const [hh = "", mm = ""] = timePart.split(":") setScheduleYear(y) setScheduleMonth(m) setScheduleDay(d) setScheduleHour(hh) setScheduleMinute(mm.slice(0, 2)) }, [scheduleMenuOpen, bulkScheduledAt]) const fetchData = useCallback(async (currentOffset: number) => { setLoading(true) setError(false) try { const [notifRes, unreadRes] = await Promise.all([ getNotifications(PAGE_SIZE, currentOffset), getUnreadCount(), ]) setNotifications(notifRes.data.notifications ?? []) setTotalCount(notifRes.data.total_count) setGlobalUnread(unreadRes.data.unread) } catch { setError(true) } finally { setLoading(false) } }, []) useEffect(() => { fetchData(offset) }, [offset, fetchData]) const handleToggleRead = useCallback(async (id: string, currentlyRead: boolean) => { setTogglingIds((prev) => new Set(prev).add(id)) try { if (currentlyRead) { await markAsUnread(id) } else { await markAsRead(id) } setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, is_read: !currentlyRead } : n)), ) setGlobalUnread((prev) => (currentlyRead ? prev + 1 : Math.max(0, prev - 1))) } catch { // silently fail — user can retry } finally { setTogglingIds((prev) => { const next = new Set(prev) next.delete(id) return next }) } }, []) const handleMarkAllRead = useCallback(async () => { setBulkLoading(true) try { await markAllRead() setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true }))) setGlobalUnread(0) } catch { // silently fail } finally { setBulkLoading(false) } }, []) const handleMarkAllUnread = useCallback(async () => { setBulkLoading(true) try { await markAllUnread() setNotifications((prev) => prev.map((n) => ({ ...n, is_read: false }))) setGlobalUnread(totalCount) } catch { // silently fail } finally { setBulkLoading(false) } }, [totalCount]) const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE)) const currentPage = Math.floor(offset / PAGE_SIZE) + 1 const startEntry = totalCount === 0 ? 0 : offset + 1 const endEntry = Math.min(offset + PAGE_SIZE, totalCount) const getPageNumbers = () => { const pages: (number | string)[] = [] if (totalPages <= 7) { for (let i = 1; i <= totalPages; i++) pages.push(i) } else { pages.push(1, 2, 3) if (currentPage > 4) pages.push("...") if (currentPage > 3 && currentPage < totalPages - 2) pages.push(currentPage) if (currentPage < totalPages - 3) pages.push("...") pages.push(totalPages) } return pages } const filteredNotifications = notifications.filter((n) => { if (channelFilter !== "all" && n.delivery_channel !== channelFilter) return false if (activeStatusTab === "read" && !n.is_read) return false if (activeStatusTab === "unread" && n.is_read) return false if (typeFilter !== "all" && n.type !== typeFilter) return false if (levelFilter !== "all" && n.level !== levelFilter) return false if (searchTerm.trim()) { const q = searchTerm.toLowerCase() const haystack = [ getNotificationTitle(n), getNotificationMessage(n), formatTypeLabel(n.type), n.delivery_channel, n.level, ] .filter(Boolean) .join(" ") .toLowerCase() if (!haystack.includes(q)) return false } return true }) const handleOpenDetail = (notification: Notification) => { setSelectedNotification(notification) setDetailOpen(true) } return (
{/* Header */}
Notifications

Notifications

{totalCount > 0 && {totalCount}} {globalUnread > 0 && {globalUnread} unread}
{/* Bulk actions */} {!loading && !error && (
{notifications.length > 0 && ( <> {globalUnread > 0 ? ( ) : ( )} )}
)}
{/* Summary cards */} {!loading && !error && (

Total notifications

{totalCount.toLocaleString()}

Unread

{globalUnread.toLocaleString()}

Channels used

{Array.from(new Set(notifications.map((n) => n.delivery_channel))).length || "—"}

)} {/* Loading */} {loading && (
)} {/* Error */} {!loading && error && ( Failed to load notifications. )} {/* Empty */} {!loading && !error && notifications.length === 0 && (
No notifications yet When you receive notifications, they'll appear here.
)} {/* Filters + table */} {!loading && !error && notifications.length > 0 && ( <> {/* Status tabs */}
{(["all", "unread", "read"] as const).map((tab) => ( ))}
{/* Filters */}
setSearchTerm(e.target.value)} />
Channel setChannelFilter(value as typeof channelFilter)} > All Push SMS
Type All types {Array.from(new Set(notifications.map((n) => n.type))).map((t) => ( {formatTypeLabel(t)} ))}
Level All levels {Array.from(new Set(notifications.map((n) => n.level))).map((lvl) => ( {lvl} ))}
Type Title Message Channel Status Created Actions {filteredNotifications.length === 0 ? (

No notifications match your filters

Try adjusting your filters

) : ( filteredNotifications.map((n) => { const config = TYPE_CONFIG[n.type] ?? DEFAULT_TYPE_CONFIG const Icon = config.icon const isToggling = togglingIds.has(n.id) return ( handleOpenDetail(n)} >
{formatTypeLabel(n.type)}

{getNotificationTitle(n)}

{getNotificationMessage(n)}

{n.delivery_channel} {n.is_read ? "Read" : "Unread"} {formatTimestamp(n.timestamp)}
e.stopPropagation()} >
) }) )}
Showing {startEntry}-{endEntry} of {totalCount} entries Rows per page
{getPageNumbers().map((n, idx) => typeof n === "string" ? ( ... ) : ( ), )}
)} {/* Detail dialog */} {selectedNotification && ( {(() => { const Icon = (TYPE_CONFIG[selectedNotification.type] ?? DEFAULT_TYPE_CONFIG).icon return })()} {getNotificationTitle(selectedNotification)} Sent via {selectedNotification.delivery_channel} ·{" "} {formatTimestamp(selectedNotification.timestamp)}

{getNotificationMessage(selectedNotification)}

Type

{formatTypeLabel(selectedNotification.type)}

Level

{selectedNotification.level}

Channel

{selectedNotification.delivery_channel}

Delivery status

{selectedNotification.delivery_status}

)} {/* Bulk send dialog */} Send notification Send a bulk SMS, email, or push notification to users.
{ e.preventDefault() if (!bulkMessage.trim()) { toast.error("Message is required") return } const userIds = bulkUserIds try { setBulkSending(true) if (bulkChannel === "sms") { if (userIds.length === 0) { toast.error("User IDs are required for bulk SMS") setBulkSending(false) return } await sendBulkSms({ message: bulkMessage.trim(), user_ids: userIds, ...(bulkScheduledAt ? { scheduled_at: bulkScheduledAt } : {}), }) } else if (bulkChannel === "email") { const form = new FormData() if (!bulkTitle.trim()) { toast.error("Subject is required for bulk email") setBulkSending(false) return } form.append("subject", bulkTitle.trim()) form.append("message", bulkMessage.trim()) if (bulkRole.trim()) form.append("role", bulkRole.trim()) if (userIds.length > 0) { form.append("user_ids", JSON.stringify(userIds)) } if (bulkScheduledAt) form.append("scheduled_at", bulkScheduledAt) if (bulkFile) form.append("file", bulkFile) await sendBulkEmail(form) } else { const form = new FormData() if (!bulkTitle.trim()) { toast.error("Title is required for bulk push") setBulkSending(false) return } form.append("title", bulkTitle.trim()) form.append("message", bulkMessage.trim()) if (bulkRole.trim()) form.append("role", bulkRole.trim()) if (userIds.length > 0) { form.append("user_ids", JSON.stringify(userIds)) } if (bulkScheduledAt) form.append("scheduled_at", bulkScheduledAt) if (bulkFile) form.append("file", bulkFile) await sendBulkPush(form) } toast.success("Notification scheduled", { description: bulkScheduledAt ? "Notification has been scheduled successfully." : "Notification has been sent successfully.", }) setBulkTitle("") setBulkMessage("") setBulkRole("") setBulkUserIds([]) setBulkScheduledAt("") setBulkFile(null) setBulkChannel("sms") setBulkOpen(false) } catch (err: any) { const msg = err?.response?.data?.message || "Failed to send notification. Please try again." toast.error("Failed to send notification", { description: msg }) } finally { setBulkSending(false) } }} >
setBulkTitle(e.target.value)} />