import { SpinnerIcon } from "@/components/ui/spinner-icon"; import { BadgeCheck, Bell, BookOpen, CheckCircle2, ChevronDown, CreditCard, DollarSign, FolderOpen, HelpCircle, PlayCircle, RefreshCw, RotateCcw, TrendingDown, TrendingUp, Users, UsersRound, Video, } from "lucide-react"; import { useEffect, useState, type ElementType, type ReactNode } from "react"; import { Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis, } from "recharts"; import { getDashboard } from "../../api/analytics.api"; import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"; import alertSrc from "../../assets/Alert.svg"; import { AcademyAnalyticsOverview } from "../../components/analytics/AcademyAnalyticsOverview"; import { AnalyticsTimeRangeFilter } from "../../components/analytics/AnalyticsTimeRangeFilter"; import { getDashboardFilterLabel } from "../../components/analytics/AnalyticsTimeRangeFilter.shared"; import { MonthlyRevenueBarChart, MonthlyRevenueTrendPanel, SensitiveYtdValue, analyticsSoftCardClass } from "../../components/analytics/SubscriptionRevenueVisuals"; import { SUBSCRIPTION_CHART_COLORS } from "../../components/analytics/SubscriptionRevenueVisuals.shared"; import { Badge } from "../../components/ui/badge"; import { Button } from "../../components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"; import { SensitiveChart, SensitiveRevealProvider, } from "../../components/ui/sensitive-value"; import { aggregateRevenueByMonth, formatAnalyticsLabel, formatAnalyticsSeriesDate, formatPercentRate, formatRevenueAxisTick, getPrimaryQuestionTypeSummary, getSeriesPeriodLabel, getSubscriptionMetrics, getVideoLessonsSummary, } from "../../lib/analytics"; import { formatAppDateTime } from "../../lib/datetime"; import { isUnassignedLabel } from "../../lib/displayValue.shared"; import { displayUserAgeGroup, displayUserCountry, displayUserEducationLevel, displayUserKnowledgeLevel, displayUserLanguageChallenge, displayUserLearningGoal, displayUserOccupation, displayUserRegion, mergeAnalyticsRowsByDisplayLabel, } from "../../lib/userProfileFieldDisplay"; import { cn } from "../../lib/utils"; import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"; const PIE_COLORS = SUBSCRIPTION_CHART_COLORS function genderAnalyticsRowLabel(label: string): string { const trimmed = label?.trim() ?? "" if ( isUnassignedLabel(trimmed) || trimmed.toUpperCase() === "OTHER" || trimmed.toLowerCase() === "unknown" ) { return "unassigned" } return formatAnalyticsLabel(label) } function formatDate(dateStr: string) { return formatAnalyticsSeriesDate(dateStr) } function formatNumber(n: number) { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M` if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K` return n.toLocaleString() } function KpiCard({ icon: Icon, label, value, sub, trend, className, }: { icon: ElementType label: string value: ReactNode sub?: ReactNode trend?: "up" | "down" | "neutral" className?: string }) { return (
{label}
{value}
{sub && (
{trend === "up" && } {trend === "down" && } {sub}
)}
) } function BreakdownList({ title, data, total, formatRowLabel, showPercent = true, }: { title: string data: LabelCount[] total?: number scrollable?: boolean formatRowLabel?: (label: string) => string showPercent?: boolean }) { const labelFn = formatRowLabel ?? formatAnalyticsLabel const merged = mergeAnalyticsRowsByDisplayLabel(data, labelFn).filter( (row) => row.label.trim().toUpperCase() !== "OTHER", ) const computedTotal = total ?? merged.reduce((s, d) => s + d.count, 0) return ( {title} {merged.length > 0 ? (
{merged.map((item, i) => { const pct = computedTotal > 0 ? (item.count / computedTotal) * 100 : 0 const displayLabel = item.label return (
{displayLabel}
{item.count.toLocaleString()} {showPercent ? `(${pct.toFixed(0)}%)` : ""}
) })}
) : (
No data available
)} ) } function DonutCard({ title, data, centerLabel, centerValue, }: { title: string data: { name: string; value: number; color: string }[] centerLabel?: string centerValue?: string }) { return ( {title} {data.length > 0 ? (
{data.map((entry) => ( ))} {centerLabel && (
{centerValue} {centerLabel}
)}
{data.map((s) => (
{s.name}
{s.value.toLocaleString()}
))}
) : (
No data available
)}
) } function Section({ title, icon: Icon, count, defaultOpen = true, children, }: { title: string icon: React.ElementType count?: number defaultOpen?: boolean children: React.ReactNode }) { const [open, setOpen] = useState(defaultOpen) return (
{children}
) } const DEFAULT_FILTERS: DashboardFilters = { mode: "all_time" } export function AnalyticsPage() { const [dashboard, setDashboard] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const [activeSummaryTab, setActiveSummaryTab] = useState<"key" | "content" | "operations">("key") const [filters, setFilters] = useState(DEFAULT_FILTERS) const fetchData = async (nextFilters: DashboardFilters = filters) => { setLoading(true) setError(false) try { const res = await getDashboard(nextFilters) setDashboard(res.data) } catch { setError(true) } finally { setLoading(false) } } useEffect(() => { fetchData(filters) // eslint-disable-next-line react-hooks/exhaustive-deps }, [filters]) if (!dashboard && loading) { return (
Analytics
Loading analytics…
) } if (error || !dashboard) { return (
Analytics
Failed to load analytics data.
) } const { users, subscriptions, payments, courses, content, notifications, team, videos } = dashboard const subscriptionMetrics = getSubscriptionMetrics(subscriptions) const seriesPeriodLabel = getSeriesPeriodLabel(dashboard.date_filter) const examPrep = courses.exam_prep const registrationData = users.registrations_last_30_days.map((d) => ({ date: formatDate(d.date), count: d.count, })) const snapshot = subscriptions.snapshot const renewal = subscriptions.renewal const periodFilterLabel = getDashboardFilterLabel(filters) const newThisPeriod = renewal && renewal.first_time_subscriptions + renewal.returning_subscriptions > 0 ? renewal.first_time_subscriptions + renewal.returning_subscriptions : subscriptions.total_subscriptions const subscriptionData = subscriptions.new_subscriptions_last_30_days.map((d) => ({ date: formatDate(d.date), count: d.count, })) const revenueData = payments.revenue_last_30_days.map((d) => ({ date: formatDate(d.date), revenue: d.revenue, })) const dateFilter = dashboard.date_filter const useMonthlyRevenueTrend = dateFilter?.mode === "year" || dateFilter?.mode === "all_time" || filters.mode === "year" || filters.mode === "all_time" const monthlyTrendYear = (dateFilter?.mode === "year" && dateFilter.year) || (filters.mode === "year" && filters.year) || new Date().getFullYear() const monthlyRevenueTrendData = useMonthlyRevenueTrend ? aggregateRevenueByMonth(payments.revenue_last_30_days, monthlyTrendYear) : revenueData const notifByTypePie = notifications.by_type.slice(0, 8).map((s, i) => ({ name: s.label, value: s.count, color: PIE_COLORS[i % PIE_COLORS.length], })) const dropOffData = videos?.drop_off_by_checkpoint.map((d) => ({ checkpoint: `${d.checkpoint_percent}%`, checkpointPercent: d.checkpoint_percent, dropOffRate: Number((d.drop_off_rate * 100).toFixed(1)), viewersReached: d.viewers_reached, totalSessions: d.total_sessions, })) ?? [] const retentionData = videos?.drop_off_by_checkpoint.map((d) => ({ checkpoint: `${d.checkpoint_percent}%`, viewers: d.viewers_reached, })) ?? [] const generatedAt = formatAppDateTime(dashboard.generated_at) return (
{/* Header */}
Analytics

Academy performance

{getDashboardFilterLabel(filters)} · Generated {generatedAt}
{loading && (
Updating analytics for {getDashboardFilterLabel(filters)}…
)}
{activeSummaryTab === "key" && } {activeSummaryTab === "operations" && ( <> {/* ─── User Analytics ─── */}
User Registrations
{users.total_users.toLocaleString()} +{users.new_today} today
{seriesPeriodLabel}

Profile & demographics

{(users.by_knowledge_level?.length ?? 0) > 0 ? ( ) : null}

Learning goals & challenges

{/* ─── Subscriptions & Revenue ─── */}
0 ? "down" : "neutral"} /> 0 ? "up" : "neutral"} /> 0 ? "up" : "neutral"} /> 0 ? "up" : "neutral"} />
} ytdLabel="Period total" >
New Subscriptions
Daily new subscriptions · {periodFilterLabel}
{seriesPeriodLabel}
Daily Revenue
Successful payments · ETB · {periodFilterLabel}
{seriesPeriodLabel}
[`ETB ${Number(v).toLocaleString()}`, "Revenue"]} contentStyle={{ borderRadius: 10, border: "1px solid #E8E8E8", boxShadow: "0 8px 24px rgba(0,0,0,0.08)", fontSize: 12, }} />
{/* ─── Notifications ─── */}
{/* ─── Team ─── */}
)} {activeSummaryTab === "content" && ( <>
0 ? "up" : "neutral"} /> 0 ? "up" : "neutral"} />
{/* ─── Course Management ─── */} {examPrep && (
{examPrep && ( )}
)} {/* ─── Content Breakdown ─── */}
{/* ─── Video Analytics ─── */} {videos && (
0 ? "up" : "neutral"} /> = 0.25 ? "up" : "neutral"} /> 0 ? "up" : "neutral"} />
Viewer Retention by Checkpoint
Viewers still watching at each progress milestone
{seriesPeriodLabel}
{retentionData.length > 0 ? ( [Number(v).toLocaleString(), "Viewers"]} contentStyle={{ borderRadius: 12, border: "1px solid #E0E0E0", boxShadow: "0 10px 30px rgba(0,0,0,0.08)", fontSize: 12, }} /> ) : (
No checkpoint data available
)}
Drop-off Rate by Checkpoint
Share of sessions that stopped before each milestone
{seriesPeriodLabel}
{dropOffData.length > 0 ? ( `${v}%`} domain={[0, 100]} /> { const row = props?.payload as (typeof dropOffData)[number] | undefined return [ `${Number(v).toFixed(1)}% drop-off`, `${row?.viewersReached?.toLocaleString() ?? 0} viewers reached`, ] }} contentStyle={{ borderRadius: 12, border: "1px solid #E0E0E0", boxShadow: "0 10px 30px rgba(0,0,0,0.08)", fontSize: 12, }} /> ) : (
No drop-off data available
)}
{dropOffData.length > 0 && (
({ label: `${d.checkpointPercent}% — ${d.viewersReached} viewers (${d.dropOffRate}% drop-off)`, count: d.viewersReached, }))} total={videos.total_watch_sessions} />
)}
)} )}
) }