import { useEffect, useState, useCallback } from "react" import { Bell, BellOff, AlertTriangle, Info, AlertCircle, CheckCircle2, ChevronLeft, ChevronRight, Megaphone, UserPlus, CreditCard, BookOpen, Video, ShieldAlert, Loader2, MailOpen, Mail, CheckCheck, MailX, Search, } 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 { FileUpload } from "../../components/ui/file-upload" import { cn } from "../../lib/utils" import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead, markAllUnread, } from "../../api/notifications.api" import { getTeamMembers } from "../../api/team.api" import type { Notification } from "../../types/notification.types" import type { TeamMember } from "../../types/team.types" 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 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 */}
{notification.payload.headline} {notification.level}

{notification.payload.message}

{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 [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 [composeChannels, setComposeChannels] = useState>(["push"]) const [composeAudience, setComposeAudience] = useState<"all" | "selected">("all") const [teamRecipients, setTeamRecipients] = useState([]) const [recipientsLoading, setRecipientsLoading] = useState(false) const [selectedRecipientIds, setSelectedRecipientIds] = useState([]) const [composeTitle, setComposeTitle] = useState("") const [composeMessage, setComposeMessage] = useState("") const [sending, setSending] = useState(false) const [composeOpen, setComposeOpen] = useState(false) const [composeImage, setComposeImage] = useState(null) 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 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 = [ n.payload.headline, n.payload.message, 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) } const handleComposeSubmit = async (e: React.FormEvent) => { e.preventDefault() if (!composeTitle.trim() || !composeMessage.trim()) return if (composeChannels.length === 0) return setSending(true) try { // Hook up to backend send API here when available. // For now, we just reset the form after a short delay for UI feedback. await new Promise((resolve) => setTimeout(resolve, 400)) setComposeTitle("") setComposeMessage("") setComposeAudience("all") setComposeChannels(["push"]) setSelectedRecipientIds([]) setComposeImage(null) setComposeOpen(false) } finally { setSending(false) } } // Lazy-load users for recipient selection when compose dialog first opens useEffect(() => { if (!composeOpen || teamRecipients.length > 0 || recipientsLoading) return setRecipientsLoading(true) getTeamMembers(1, 50) .then((res) => { setTeamRecipients(res.data.data ?? []) }) .catch(() => { setTeamRecipients([]) }) .finally(() => { setRecipientsLoading(false) }) }, [composeOpen, teamRecipients.length, recipientsLoading]) 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
Type
Level
Type Title Message Channel Status Created Actions {filteredNotifications.length === 0 ? ( No notifications match 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)}

{n.payload.headline}

{n.payload.message}

{n.delivery_channel} {n.is_read ? "Read" : "Unread"} {formatTimestamp(n.timestamp)}
e.stopPropagation()} >
) }) )}
{/* Pagination */} {totalPages > 1 && (
Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, totalCount)} of {totalCount}
{currentPage} / {totalPages}
)} )} {/* Detail dialog */} {selectedNotification && ( {(() => { const Icon = (TYPE_CONFIG[selectedNotification.type] ?? DEFAULT_TYPE_CONFIG).icon return })()} {selectedNotification.payload.headline} Sent via {selectedNotification.delivery_channel} ·{" "} {formatTimestamp(selectedNotification.timestamp)}

{selectedNotification.payload.message}

Type

{formatTypeLabel(selectedNotification.type)}

Level

{selectedNotification.level}

Channel

{selectedNotification.delivery_channel}

Delivery status

{selectedNotification.delivery_status}

)} {/* Compose dialog */} Create notification Send a one-off push or SMS notification to your users.

Channel

Audience

setComposeTitle(e.target.value)} />