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"
import { Button } from "@/components/ui/button"

export function AnalyticsTab() {
  const [period, setPeriod] = useState<'7days' | '30days' | '90days'>('30days')
  const { analytics, loading: analyticsLoading, fetchAnalytics } = useBackInStockAnalytics()
  const { notifications, page: notificationPage, pages: notificationPages, loading: notificationsLoading, fetchNotifications } = 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 <Badge variant="default" className="bg-blue-500">Sent</Badge>
      case 'failed':
        return <Badge variant="destructive">Failed</Badge>
      case 'bounced':
        return <Badge variant="outline">Bounced</Badge>
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  if (analyticsLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Period Selector */}
      <div className="flex justify-end">
        <Select value={period} onValueChange={(v) => setPeriod(v as typeof period)}>
          <SelectTrigger className="w-[180px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="7days">Last 7 days</SelectItem>
            <SelectItem value="30days">Last 30 days</SelectItem>
            <SelectItem value="90days">Last 90 days</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Stats Grid */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Subscriptions</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {stats.totalSubscriptions}
            </div>
            <p className="text-xs text-muted-foreground">
              {stats.activeSubscriptions} active
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Emails Sent</CardTitle>
            <Mail className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {stats.totalNotificationsSent}
            </div>
            <p className="text-xs text-muted-foreground">
              Back in stock notifications
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Conversion Rate</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {stats.conversionRate}%
            </div>
            <p className="text-xs text-muted-foreground">
              Sent emails resulting in purchases
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Additional Stats Row */}
      <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Open Rate</CardTitle>
              <Eye className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.openRate}%</div>
              <p className="text-xs text-muted-foreground">
                Emails opened
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Click Rate</CardTitle>
              <MousePointer className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.clickRate}%</div>
              <p className="text-xs text-muted-foreground">
                Links clicked
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Conversions</CardTitle>
              <ShoppingCart className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.conversions || 0}</div>
              <p className="text-xs text-muted-foreground">
                Purchases after notification
              </p>
            </CardContent>
          </Card>
        </div>

      {/* Top Products */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <BarChart3 className="h-5 w-5" />
            Top Products by Subscriptions
          </CardTitle>
          <CardDescription>
            Products with the most back-in-stock subscriptions
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {topProducts.map((product, index) => (
              <div key={product.product_id} className="flex items-center">
                <div className="w-8 text-sm text-muted-foreground">#{index + 1}</div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">
                    {product.product_name}
                  </p>
                </div>
                <div className="ml-4 flex items-center gap-2">
                  <div className="h-2 bg-primary rounded-full" style={{ 
                    width: `${Math.max(20, (product.subscription_count / (topProducts[0]?.subscription_count || 1)) * 100)}px` 
                  }} />
                  <span className="text-sm font-medium w-8 text-right">
                    {product.subscription_count}
                  </span>
                </div>
              </div>
            ))}
            {topProducts.length === 0 && (
              <p className="text-center text-sm text-muted-foreground py-4">
                No subscription data yet
              </p>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Sent Emails / Notification Log */}
      <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Mail className="h-5 w-5" />
              Sent Notifications
            </CardTitle>
            <CardDescription>
              Email notifications sent to subscribers
            </CardDescription>
          </CardHeader>
          <CardContent>
            {notificationsLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
            ) : notifications.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                No notifications sent yet. They will appear here when products come back in stock.
              </div>
            ) : (
              <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Email</TableHead>
                    <TableHead>Product</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Sent</TableHead>
                    <TableHead>Opened</TableHead>
                    <TableHead>Clicked</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {notifications.map((notif) => (
                    <TableRow key={notif.id}>
                      <TableCell className="font-medium">{notif.email}</TableCell>
                      <TableCell>{notif.product_name || `Product #${notif.product_id}`}</TableCell>
                      <TableCell>{getStatusBadge(notif.status)}</TableCell>
                      <TableCell>
                        {new Date(notif.sent_at).toLocaleDateString()}
                      </TableCell>
                      <TableCell>
                        {notif.opened_at ? (
                          <Badge variant="outline" className="text-green-600">Yes</Badge>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {notif.clicked_at ? (
                          <Badge variant="outline" className="text-green-600">Yes</Badge>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              {notificationPages > 1 && (
                <div className="mt-4 flex items-center justify-between border-t pt-4">
                  <span className="text-sm text-muted-foreground">Page {notificationPage} of {notificationPages}</span>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" disabled={notificationPage <= 1} onClick={() => fetchNotifications({ page: notificationPage - 1 })}>
                      Previous
                    </Button>
                    <Button variant="outline" size="sm" disabled={notificationPage >= notificationPages} onClick={() => fetchNotifications({ page: notificationPage + 1 })}>
                      Next
                    </Button>
                  </div>
                </div>
              )}
              </>
            )}
          </CardContent>
        </Card>

    </div>
  )
}
