import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
import { Card, CardContent } from "@/components/ui/card"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { Skeleton } from "@/components/ui/skeleton"
import { Sparkles, RotateCcw, TrendingUp, Clock, CalendarClock, EyeOff, Info } from "lucide-react"
import config from "@/config"

interface Stats {
  unfeatured_new: number
  back_in_stock_ready: number
  high_score_available: number
  last_campaign_date: string
  avg_days_since_featured: number
  never_featured: number
}

export function NewsletterStats() {
  const { data } = useQuery<Stats>({
    queryKey: ["newsletter-stats"],
    queryFn: async () => {
      const res = await apiFetch(`${config.apiUrl}/newsletter/stats`)
      if (!res.ok) throw new Error("Failed to fetch stats")
      return res.json()
    },
  })

  if (!data) {
    return (
      <div className="grid gap-4 grid-cols-2 md:grid-cols-3 xl:grid-cols-6">
        {Array.from({ length: 6 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <Skeleton className="h-3.5 w-3.5 rounded" />
                <Skeleton className="h-3 w-20" />
              </div>
              <Skeleton className="h-8 w-16 mt-1" />
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  const stats = [
    {
      label: "Unfeatured New",
      value: data.unfeatured_new?.toLocaleString() ?? "—",
      icon: Sparkles,
      tooltip: "New products (< 31 days) that haven't appeared in any newsletter yet. If this is high, prioritize new arrivals today.",
    },
    {
      label: "Back in Stock Ready",
      value: data.back_in_stock_ready?.toLocaleString() ?? "—",
      icon: RotateCcw,
      tooltip: "Restocked products that haven't been featured since their restock date. These are time-sensitive — customers are waiting and stock could sell through.",
    },
    {
      label: "High Score Available",
      value: data.high_score_available?.toLocaleString() ?? "—",
      icon: TrendingUp,
      tooltip: "Products scoring 40+ that haven't been featured in the last 2 days. Shows how deep your bench of strong picks is for today's send.",
    },
    {
      label: "Last Campaign",
      value: data.last_campaign_date ? new Date(data.last_campaign_date).toLocaleDateString() : "—",
      icon: Clock,
      tooltip: "Date of the most recent synced campaign. Useful to confirm your Klaviyo sync is up to date.",
    },
    {
      label: "Avg Days Since Featured",
      value: data.avg_days_since_featured ?? "—",
      icon: CalendarClock,
      tooltip: "Average days since in-stock products were last featured. If this is climbing, you're not cycling through enough of your catalog.",
    },
    {
      label: "Never Featured",
      value: data.never_featured?.toLocaleString() ?? "—",
      icon: EyeOff,
      tooltip: "Visible, in-stock products that have never appeared in any newsletter. Your untapped opportunity pool.",
    },
  ]

  return (
    <TooltipProvider>
      <div className="grid gap-4 grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
        {stats.map((s) => (
          <Card key={s.label}>
            <CardContent className="p-4">
              <div className="flex items-center gap-2 text-muted-foreground text-xs font-medium">
                <s.icon className="h-3.5 w-3.5 shrink-0" />
                <span className="truncate">{s.label}</span>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Info className="h-3 w-3 shrink-0 cursor-help opacity-50 hover:opacity-100 transition-opacity" />
                  </TooltipTrigger>
                  <TooltipContent side="bottom" className="max-w-[240px]">
                    <p className="text-xs font-medium">{s.label}</p>
                    <p>{s.tooltip}</p>
                  </TooltipContent>
                </Tooltip>
              </div>
              <p className="text-2xl font-bold mt-1">{s.value}</p>
            </CardContent>
          </Card>
        ))}
      </div>
    </TooltipProvider>
  )
}
