import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { BarChart3, Users, Mail, ShoppingCart, TrendingUp, Loader2, MousePointer, Eye } from "lucide-react" import { useState, useEffect } from "react" import { useBackInStockAnalytics, useBackInStockNotifications } from "../../hooks/use-back-in-stock" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" import { Badge } from "@/components/ui/badge" export function AnalyticsTab() { const [period, setPeriod] = useState<'7days' | '30days' | '90days'>('30days') const { analytics, loading: analyticsLoading, fetchAnalytics } = useBackInStockAnalytics() const { notifications, loading: notificationsLoading } = useBackInStockNotifications() // Refetch analytics when period changes useEffect(() => { fetchAnalytics(period) }, [period, fetchAnalytics]) const stats = analytics?.stats ?? { totalSubscriptions: 0, activeSubscriptions: 0, totalNotificationsSent: 0, notificationsOpened: 0, notificationsClicked: 0, conversions: 0, openRate: 0, clickRate: 0, conversionRate: 0, } const topProducts = analytics?.topProducts ?? [] const getStatusBadge = (status: string) => { switch (status) { case 'sent': return Sent case 'failed': return Failed case 'bounced': return Bounced default: return {status} } } if (analyticsLoading) { return (
) } return (
{/* Period Selector */}
{/* Stats Grid */}
Total Subscriptions
{stats.totalSubscriptions}

{stats.activeSubscriptions} active

Emails Sent
{stats.totalNotificationsSent}

Back in stock notifications

Conversion Rate
{stats.conversionRate}%

Subscriptions to purchases

{/* Additional Stats Row */}
Open Rate
{stats.openRate}%

Emails opened

Click Rate
{stats.clickRate}%

Links clicked

Conversions
{stats.conversions || 0}

Purchases after notification

{/* Top Products */} Top Products by Subscriptions Products with the most back-in-stock subscriptions
{topProducts.map((product, index) => (
#{index + 1}

{product.product_name}

{product.subscription_count}
))} {topProducts.length === 0 && (

No subscription data yet

)}
{/* Sent Emails / Notification Log */} Sent Notifications Email notifications sent to subscribers {notificationsLoading ? (
) : notifications.length === 0 ? (
No notifications sent yet. They will appear here when products come back in stock.
) : ( Email Product Status Sent Opened Clicked {notifications.slice(0, 10).map((notif) => ( {notif.email} {notif.product_name || `Product #${notif.product_id}`} {getStatusBadge(notif.status)} {new Date(notif.sent_at).toLocaleDateString()} {notif.opened_at ? ( Yes ) : ( - )} {notif.clicked_at ? ( Yes ) : ( - )} ))}
)}
) }