import { useState, useMemo } from "react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
} from "@/components/ui/chart"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  XAxis,
  YAxis,
} from "recharts"
import {
  Loader2,
  TrendingUp,
  ShoppingCart,
  Mail,
  MousePointerClick,
  DollarSign,
  Users,
  Ticket,
  Package,
  UserX,
  CheckCircle2,
  XCircle,
  ExternalLink,
  Eye,
  BarChart3,
  Download,
} from "lucide-react"
import { useAbandonedCartAnalytics } from "../../hooks/use-abandoned-cart"
import type { DailyStat } from "../../types"
import { toast } from "sonner"

/* ───────────────── Helpers ───────────────── */

function formatCurrency(amount: number, currency: string) {
  try {
    return new Intl.NumberFormat(undefined, {
      style: "currency",
      currency: currency || "USD",
    }).format(amount)
  } catch {
    return `${currency} ${amount.toFixed(2)}`
  }
}

function formatDate(dateStr: string) {
  if (!dateStr) return "—"
  const date = new Date(dateStr)
  return date.toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  })
}

function formatShortDate(dateStr: string) {
  const date = new Date(dateStr)
  return date.toLocaleDateString(undefined, { month: "short", day: "numeric" })
}

/* ───────────────── Chart Configs ───────────────── */

const cartsChartConfig = {
  abandoned: {
    label: "Abandoned",
    color: "#f97316",
  },
  recovered: {
    label: "Recovered",
    color: "#22c55e",
  },
} satisfies ChartConfig

const revenueChartConfig = {
  revenue: {
    label: "Revenue",
    color: "#00226b",
  },
} satisfies ChartConfig

const emailEngagementConfig = {
  opened: {
    label: "Opened",
    color: "#00226b",
  },
  clicked: {
    label: "Clicked",
    color: "#22c55e",
  },
} satisfies ChartConfig

/* ───────────────── Period Filter ───────────────── */

type Period = "7d" | "30d"

function filterByPeriod(stats: DailyStat[], period: Period): DailyStat[] {
  if (!stats || stats.length === 0) return []
  const days = period === "7d" ? 7 : 30
  return stats.slice(-days)
}

/* ───────────────── Main Component ───────────────── */

export function AnalyticsTab() {
  const { analytics, loading } = useAbandonedCartAnalytics()
  const [period, setPeriod] = useState<Period>("30d")
  const [exporting, setExporting] = useState(false)
  const [exportingCarts, setExportingCarts] = useState(false)

  const filteredStats = useMemo(
    () => filterByPeriod(analytics?.dailyStats || [], period),
    [analytics?.dailyStats, period]
  )

  const handleExportAnalytics = async () => {
    try {
      setExporting(true)
      const apiUrl = (window as any).swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
      const nonce = (window as any).swiftCommerceData?.restNonce || ''
      const response = await fetch(`${apiUrl}/abandoned-cart/export-analytics`, {
        headers: { 'X-WP-Nonce': nonce },
      })
      const data = await response.json()
      if (data.success && data.csv) {
        const blob = new Blob([data.csv], { type: 'text/csv;charset=utf-8;' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `cart-recovery-analytics-${new Date().toISOString().slice(0, 10)}.csv`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
      }
    } catch (error) {
      console.error('Failed to export analytics:', error)
    } finally {
      setExporting(false)
    }
  }

  const handleExportCarts = async () => {
    try {
      setExportingCarts(true)
      const apiUrl = (window as any).swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1'
      const nonce = (window as any).swiftCommerceData?.restNonce || ''
      const response = await fetch(`${apiUrl}/abandoned-cart/export`, {
        headers: { 'X-WP-Nonce': nonce },
      })
      const data = await response.json()
      if (data.success && data.csv) {
        const blob = new Blob([data.csv], { type: 'text/csv;charset=utf-8;' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `abandoned-carts-${new Date().toISOString().slice(0, 10)}.csv`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        if (data.truncated) {
          toast.warning(`Exported the newest ${data.count} of ${data.total} carts.`)
        }
      }
    } catch (error) {
      console.error('Failed to export carts:', error)
    } finally {
      setExportingCarts(false)
    }
  }

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

  if (!analytics) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center p-6">
        <TrendingUp className="h-12 w-12 text-muted-foreground/50 mb-4" />
        <h3 className="text-lg font-medium">No analytics data yet</h3>
        <p className="text-sm text-muted-foreground mt-1">
          Analytics will populate once you start tracking abandoned carts and sending recovery emails.
        </p>
      </div>
    )
  }

  const currency = analytics.currency || "USD"
  const revenueDescription = (analytics.revenueByCurrency || []).length > 1
    ? (analytics.revenueByCurrency || [])
        .map((row) => formatCurrency(row.amount, row.currency))
        .join(' · ')
    : "Paid order revenue in the store currency"

  return (
    <Tabs defaultValue="overview" className="space-y-6">
      <div className="flex items-center justify-between">
        <TabsList>
          <TabsTrigger value="overview" className="gap-1.5">
            <BarChart3 className="h-4 w-4" />
            Overview
          </TabsTrigger>
          <TabsTrigger value="emails" className="gap-1.5">
            <Mail className="h-4 w-4" />
            Emails
          </TabsTrigger>
          <TabsTrigger value="coupons" className="gap-1.5">
            <Ticket className="h-4 w-4" />
            Coupons
          </TabsTrigger>
        </TabsList>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleExportCarts} disabled={exportingCarts} className="gap-2">
            {exportingCarts ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
            Export Carts
          </Button>
          <Button variant="outline" size="sm" onClick={handleExportAnalytics} disabled={exporting} className="gap-2">
            {exporting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
            Export Analytics
          </Button>
        </div>
      </div>

      {/* ══════════════════════ OVERVIEW TAB ══════════════════════ */}
      <TabsContent value="overview" className="space-y-6">
        {/* Summary Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard
            title="Total Abandoned"
            value={analytics.totalAbandoned}
            icon={ShoppingCart}
            description="Carts flagged as abandoned"
          />
          <StatCard
            title="Total Recovered"
            value={analytics.totalRecovered}
            icon={TrendingUp}
            description="Carts successfully recovered"
          />
          <StatCard
            title="Recovery Rate"
            value={`${analytics.recoveryRate.toFixed(1)}%`}
            icon={MousePointerClick}
            description="Of abandoned carts recovered"
          />
          <StatCard
            title="Revenue Recovered"
            value={formatCurrency(analytics.revenueRecovered, currency)}
            icon={DollarSign}
            description={revenueDescription}
          />
        </div>

        {/* Carts Trend Chart */}
        {filteredStats.length > 0 && (
          <Card>
            <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
              <div>
                <CardTitle className="text-base">Cart Recovery Trend</CardTitle>
                <CardDescription>
                  Abandoned vs recovered carts over time.
                </CardDescription>
              </div>
              <PeriodSelector period={period} onChange={setPeriod} />
            </CardHeader>
            <CardContent>
              <ChartContainer config={cartsChartConfig} className="h-[280px] w-full">
                <AreaChart data={filteredStats} accessibilityLayer>
                  <defs>
                    <linearGradient id="fillAbandoned" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#f97316" stopOpacity={0.3} />
                      <stop offset="95%" stopColor="#f97316" stopOpacity={0.02} />
                    </linearGradient>
                    <linearGradient id="fillRecovered" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#22c55e" stopOpacity={0.3} />
                      <stop offset="95%" stopColor="#22c55e" stopOpacity={0.02} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="date"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={formatShortDate}
                  />
                  <YAxis
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    allowDecimals={false}
                  />
                  <ChartTooltip
                    content={<ChartTooltipContent labelFormatter={formatShortDate} />}
                  />
                  <ChartLegend content={<ChartLegendContent />} />
                  <Area
                    type="monotone"
                    dataKey="abandoned"
                    stroke="#f97316"
                    fill="url(#fillAbandoned)"
                    strokeWidth={2}
                  />
                  <Area
                    type="monotone"
                    dataKey="recovered"
                    stroke="#22c55e"
                    fill="url(#fillRecovered)"
                    strokeWidth={2}
                  />
                </AreaChart>
              </ChartContainer>
            </CardContent>
          </Card>
        )}

        {/* Revenue Trend Chart */}
        {filteredStats.length > 0 && (
          <Card>
            <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
              <div>
                <CardTitle className="text-base">Revenue Recovered</CardTitle>
                <CardDescription>
                  Daily recovered revenue ({currency}).
                </CardDescription>
              </div>
              <PeriodSelector period={period} onChange={setPeriod} />
            </CardHeader>
            <CardContent>
              <ChartContainer config={revenueChartConfig} className="h-[240px] w-full">
                <BarChart data={filteredStats} accessibilityLayer>
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="date"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={formatShortDate}
                  />
                  <YAxis
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={(v) => formatCurrency(v, currency)}
                  />
                  <ChartTooltip
                    content={
                      <ChartTooltipContent
                        labelFormatter={formatShortDate}
                        formatter={(value) => formatCurrency(Number(value), currency)}
                      />
                    }
                  />
                  <Bar
                    dataKey="revenue"
                    fill="#00226b"
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ChartContainer>
            </CardContent>
          </Card>
        )}

        {/* Customer Breakdown + Most Abandoned Products */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {/* Customer Breakdown */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <Users className="h-5 w-5" />
                Customer Breakdown
              </CardTitle>
              <CardDescription>Guest vs registered customer activity.</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-3">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Abandoned
                  </p>
                  <ProgressStat
                    label="Guest"
                    value={analytics.guestAbandoned || 0}
                    total={analytics.totalAbandoned}
                    color="bg-orange-400"
                  />
                  <ProgressStat
                    label="Registered"
                    value={analytics.loggedinAbandoned || 0}
                    total={analytics.totalAbandoned}
                    color="bg-blue-400"
                  />
                </div>
                <div className="space-y-3">
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Recovered
                  </p>
                  <ProgressStat
                    label="Guest"
                    value={analytics.guestRecovered || 0}
                    total={analytics.totalRecovered}
                    color="bg-green-400"
                  />
                  <ProgressStat
                    label="Registered"
                    value={analytics.loggedinRecovered || 0}
                    total={analytics.totalRecovered}
                    color="bg-emerald-500"
                  />
                </div>
              </div>
              {analytics.totalUnsubscribed > 0 && (
                <div className="mt-4 pt-3 border-t flex items-center justify-between text-sm">
                  <span className="flex items-center gap-1.5 text-muted-foreground">
                    <UserX className="h-4 w-4" />
                    Unsubscribed
                  </span>
                  <span className="font-medium">{analytics.totalUnsubscribed}</span>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Popular Abandoned Products */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <Package className="h-5 w-5" />
                Most Abandoned Products
              </CardTitle>
              <CardDescription>
                Products most frequently left in abandoned carts.
              </CardDescription>
            </CardHeader>
            <CardContent>
              {analytics.popularProducts && analytics.popularProducts.length > 0 ? (
                <div className="space-y-3">
                  {analytics.popularProducts.map((product, idx) => (
                    <div key={product.id || idx} className="flex items-center gap-3">
                      <span className="text-sm font-medium text-muted-foreground w-5">
                        {idx + 1}.
                      </span>
                      <div className="h-10 w-10 rounded border bg-muted flex-shrink-0 overflow-hidden">
                        {product.image ? (
                          <img
                            src={product.image}
                            alt={product.name}
                            className="h-full w-full object-cover"
                          />
                        ) : (
                          <div className="h-full w-full flex items-center justify-center">
                            <Package className="h-4 w-4 text-muted-foreground" />
                          </div>
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate">{product.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {formatCurrency(parseFloat(product.price || "0"), currency)}
                        </p>
                      </div>
                      <Badge variant="secondary" className="flex-shrink-0">
                        {product.count} {product.count === 1 ? "time" : "times"}
                      </Badge>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground text-center py-6">
                  No product data available yet.
                </p>
              )}
            </CardContent>
          </Card>
        </div>
      </TabsContent>

      {/* ══════════════════════ EMAILS TAB ══════════════════════ */}
      <TabsContent value="emails" className="space-y-6">
        {/* Email Summary Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-5 gap-4">
          <StatCard
            title="Sent"
            value={analytics.emailsSent}
            icon={Mail}
            compact
          />
          <StatCard
            title="Opened"
            value={analytics.emailsOpened}
            icon={Eye}
            compact
          />
          <StatCard
            title="Clicked"
            value={analytics.emailsClicked}
            icon={MousePointerClick}
            compact
          />
          <StatCard
            title="Open Rate"
            value={`${analytics.openRate.toFixed(1)}%`}
            icon={Eye}
            compact
          />
          <StatCard
            title="Click Rate"
            value={`${analytics.clickRate.toFixed(1)}%`}
            icon={MousePointerClick}
            compact
          />
        </div>

        {/* Email Engagement Funnel */}
        {analytics.emailsSent > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Email Engagement Funnel</CardTitle>
              <CardDescription>
                How recipients interact with your recovery emails.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <FunnelBar
                  label="Sent"
                  value={analytics.emailsSent}
                  total={analytics.emailsSent}
                  color="bg-muted-foreground/20"
                />
                <FunnelBar
                  label="Opened"
                  value={analytics.emailsOpened}
                  total={analytics.emailsSent}
                  color="bg-[#00226b]"
                />
                <FunnelBar
                  label="Clicked"
                  value={analytics.emailsClicked}
                  total={analytics.emailsSent}
                  color="bg-green-500"
                />
                <FunnelBar
                  label="Recovered"
                  value={analytics.totalRecovered}
                  total={analytics.emailsSent}
                  color="bg-emerald-500"
                />
              </div>
            </CardContent>
          </Card>
        )}

        {/* Email Engagement Over Time Chart */}
        {analytics.recentEmails && analytics.recentEmails.length > 0 && (
          <Card>
            <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
              <div>
                <CardTitle className="text-base">Email Engagement</CardTitle>
                <CardDescription>
                  Opens and clicks recorded from recovery emails.
                </CardDescription>
              </div>
              <PeriodSelector period={period} onChange={setPeriod} />
            </CardHeader>
            <CardContent>
              <ChartContainer config={emailEngagementConfig} className="h-[240px] w-full">
                <BarChart data={buildEmailDailyStats(analytics.recentEmails, period)} accessibilityLayer>
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="date"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={formatShortDate}
                  />
                  <YAxis tickLine={false} axisLine={false} tickMargin={8} allowDecimals={false} />
                  <ChartTooltip content={<ChartTooltipContent labelFormatter={formatShortDate} />} />
                  <ChartLegend content={<ChartLegendContent />} />
                  <Bar dataKey="opened" fill="#00226b" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="clicked" fill="#22c55e" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ChartContainer>
            </CardContent>
          </Card>
        )}

        {/* Recent Recovery Emails Table */}
        {analytics.recentEmails && analytics.recentEmails.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <Mail className="h-5 w-5" />
                Recent Recovery Emails
              </CardTitle>
              <CardDescription>
                Last 20 recovery emails sent with engagement status.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="pl-4">Recipient</TableHead>
                      <TableHead>Subject</TableHead>
                      <TableHead>Sent</TableHead>
                      <TableHead>Opened</TableHead>
                      <TableHead>Clicked</TableHead>
                      <TableHead className="pr-4">Cart Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {analytics.recentEmails.map((email) => (
                      <TableRow key={email.id}>
                        <TableCell className="pl-4">
                          <span className="text-sm">{email.customer_email}</span>
                        </TableCell>
                        <TableCell>
                          <span className="text-sm truncate max-w-[200px] inline-block">
                            {email.subject}
                          </span>
                        </TableCell>
                        <TableCell>
                          <span className="text-xs text-muted-foreground">
                            {formatDate(email.sent_at)}
                          </span>
                        </TableCell>
                        <TableCell>
                          {email.opened_at ? (
                            <div className="flex items-center gap-1.5">
                              <CheckCircle2 className="h-4 w-4 text-green-500" />
                              <span className="text-xs text-muted-foreground">
                                {formatDate(email.opened_at)}
                              </span>
                            </div>
                          ) : (
                            <XCircle className="h-4 w-4 text-muted-foreground/40" />
                          )}
                        </TableCell>
                        <TableCell>
                          {email.clicked_at ? (
                            <div className="flex items-center gap-1.5">
                              <ExternalLink className="h-4 w-4 text-green-500" />
                              <span className="text-xs text-muted-foreground">
                                {formatDate(email.clicked_at)}
                              </span>
                            </div>
                          ) : (
                            <XCircle className="h-4 w-4 text-muted-foreground/40" />
                          )}
                        </TableCell>
                        <TableCell className="pr-4">
                          <Badge
                            variant={
                              email.cart_status === "recovered"
                                ? "default"
                                : email.cart_status === "abandoned"
                                  ? "destructive"
                                  : "secondary"
                            }
                            className={
                              email.cart_status === "recovered"
                                ? "bg-green-100 text-green-800 hover:bg-green-100"
                                : ""
                            }
                          >
                            {email.cart_status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        )}
      </TabsContent>

      {/* ══════════════════════ COUPONS TAB ══════════════════════ */}
      <TabsContent value="coupons" className="space-y-6">
        {/* Coupon Summary Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
          <StatCard
            title="Coupons Generated"
            value={analytics.totalCoupons || 0}
            icon={Ticket}
            description="Total auto-generated coupons"
          />
          <StatCard
            title="Coupons Redeemed"
            value={analytics.couponsUsed || 0}
            icon={CheckCircle2}
            description="Used by customers"
          />
          <StatCard
            title="Redemption Rate"
            value={
              analytics.totalCoupons > 0
                ? `${(((analytics.couponsUsed || 0) / analytics.totalCoupons) * 100).toFixed(1)}%`
                : "0%"
            }
            icon={TrendingUp}
            description="Of generated coupons used"
          />
          <StatCard
            title="Coupon Revenue"
            value={formatCurrency(analytics.couponRevenue || 0, currency)}
            icon={DollarSign}
            description="Revenue from coupon orders"
          />
        </div>

        {/* Coupon Funnel */}
        {(analytics.totalCoupons || 0) > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Coupon Performance Funnel</CardTitle>
              <CardDescription>
                From generation to revenue — how your recovery coupons perform.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <FunnelBar
                  label="Generated"
                  value={analytics.totalCoupons || 0}
                  total={analytics.totalCoupons || 1}
                  color="bg-muted-foreground/20"
                />
                <FunnelBar
                  label="Redeemed"
                  value={analytics.couponsUsed || 0}
                  total={analytics.totalCoupons || 1}
                  color="bg-[#00226b]"
                />
              </div>
              <div className="mt-6 pt-4 border-t grid grid-cols-2 gap-4">
                <div className="text-center">
                  <p className="text-2xl font-bold">
                    {formatCurrency(analytics.couponRevenue || 0, currency)}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    Total Coupon Revenue
                  </p>
                </div>
                <div className="text-center">
                  <p className="text-2xl font-bold">
                    {(analytics.couponsUsed || 0) > 0
                      ? formatCurrency(
                          (analytics.couponRevenue || 0) / (analytics.couponsUsed || 1),
                          currency
                        )
                      : formatCurrency(0, currency)}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    Avg Order with Coupon
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {(analytics.totalCoupons || 0) === 0 && (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12 text-center">
              <Ticket className="h-12 w-12 text-muted-foreground/30 mb-4" />
              <h3 className="text-lg font-medium">No coupons generated yet</h3>
              <p className="text-sm text-muted-foreground mt-1 max-w-md">
                Enable coupon generation in your email sequence settings to automatically include discount codes in recovery emails.
              </p>
            </CardContent>
          </Card>
        )}
      </TabsContent>
    </Tabs>
  )
}

/* ───────────────── Sub-Components ───────────────── */

function StatCard({
  title,
  value,
  icon: Icon,
  description,
  compact,
}: {
  title: string
  value: string | number
  icon: React.ElementType
  description?: string
  compact?: boolean
}) {
  if (compact) {
    return (
      <Card>
        <CardContent className="pt-4 pb-3 px-4">
          <div className="flex items-center justify-between mb-1">
            <p className="text-xs font-medium text-muted-foreground">{title}</p>
            <Icon className="h-3.5 w-3.5 text-muted-foreground" />
          </div>
          <p className="text-xl font-bold">{value}</p>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium text-muted-foreground">{title}</CardTitle>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  )
}

function ProgressStat({
  label,
  value,
  total,
  color,
}: {
  label: string
  value: number
  total: number
  color: string
}) {
  const pct = total > 0 ? (value / total) * 100 : 0
  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <span className="text-sm">{label}</span>
        <span className="text-sm font-bold">{value}</span>
      </div>
      <div className="w-full bg-muted rounded-full h-2">
        <div
          className={`${color} h-2 rounded-full transition-all`}
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  )
}

function FunnelBar({
  label,
  value,
  total,
  color,
}: {
  label: string
  value: number
  total: number
  color: string
}) {
  const pct = total > 0 ? (value / total) * 100 : 0
  return (
    <div className="space-y-1.5">
      <div className="flex items-center justify-between text-sm">
        <span className="font-medium">{label}</span>
        <span className="text-muted-foreground">
          {value} ({pct.toFixed(1)}%)
        </span>
      </div>
      <div className="w-full bg-muted rounded-full h-3">
        <div
          className={`${color} h-3 rounded-full transition-all`}
          style={{ width: `${Math.max(pct, 2)}%` }}
        />
      </div>
    </div>
  )
}

function PeriodSelector({
  period,
  onChange,
}: {
  period: Period
  onChange: (p: Period) => void
}) {
  return (
    <div className="flex items-center rounded-md border p-0.5">
      <button
        onClick={() => onChange("7d")}
        className={`px-3 py-1 text-xs font-medium rounded transition-colors ${
          period === "7d"
            ? "bg-foreground text-background"
            : "text-muted-foreground hover:text-foreground"
        }`}
      >
        7 days
      </button>
      <button
        onClick={() => onChange("30d")}
        className={`px-3 py-1 text-xs font-medium rounded transition-colors ${
          period === "30d"
            ? "bg-foreground text-background"
            : "text-muted-foreground hover:text-foreground"
        }`}
      >
        30 days
      </button>
    </div>
  )
}

/* ───────────────── Data Helpers ───────────────── */

interface EmailDayStat {
  date: string
  opened: number
  clicked: number
}

/**
 * Build daily aggregated open/click stats from recent emails for the engagement chart.
 */
function buildEmailDailyStats(
  emails: { sent_at: string; opened_at: string | null; clicked_at: string | null }[],
  period: Period
): EmailDayStat[] {
  const days = period === "7d" ? 7 : 30
  const now = new Date()
  const map = new Map<string, EmailDayStat>()

  // Seed all dates
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(now)
    d.setDate(d.getDate() - i)
    const key = d.toISOString().slice(0, 10)
    map.set(key, { date: key, opened: 0, clicked: 0 })
  }

  // Tally opens and clicks by their respective dates
  for (const e of emails) {
    if (e.opened_at) {
      const key = new Date(e.opened_at).toISOString().slice(0, 10)
      const stat = map.get(key)
      if (stat) stat.opened++
    }
    if (e.clicked_at) {
      const key = new Date(e.clicked_at).toISOString().slice(0, 10)
      const stat = map.get(key)
      if (stat) stat.clicked++
    }
  }

  return Array.from(map.values())
}
