import { useQuery } from "@tanstack/react-query"
import { apiFetch } from '@/utils/api';
import { useState, useMemo, useContext } from "react"
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Tooltip, TooltipContent, TooltipProvider, TooltipTrigger,
} from "@/components/ui/tooltip"
import { ChevronLeft, ChevronRight, ExternalLink, Layers, Copy, Check, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react"
import { toast } from "sonner"
import { AuthContext } from "@/contexts/AuthContext"
import config from "@/config"

interface Product {
  pid: number
  title: string
  sku: string
  brand: string
  vendor: string
  price: number
  regular_price: number
  image: string
  permalink: string
  stock_quantity: number
  preorder_count: number
  sales_7d: number
  sales_30d: number
  revenue_30d: number
  current_stock: number
  on_order_qty: number
  abc_class: string
  line: string | null
  times_featured: number | null
  last_featured_at: string | null
  days_since_featured: number | null
  line_products_featured: number | null
  line_total_features: number | null
  line_last_featured_at: string | null
  line_products_featured_30d: number | null
  line_product_count: number | null
  line_days_since_featured: number | null
  effective_last_featured: string | null
  effective_days_since_featured: number | null
  age_days: number
  score: number
  is_new: boolean
  is_preorder: boolean
  is_clearance: boolean
  discount_pct: number
  is_low_stock: boolean
  is_back_in_stock: boolean
  is_daily_deal: boolean
  deal_price: number | null
  baskets: number
  notifies: number
}

interface RecommendationResponse {
  products: Product[]
  pagination: {
    total: number
    pages: number
    currentPage: number
    limit: number
  }
}

interface RecommendationTableProps {
  category: string
}

function FeaturedCell({ p }: { p: Product }) {
  const directCount = p.times_featured ?? 0
  const hasLineHistory = p.line && p.line_last_featured_at && !p.last_featured_at

  return (
    <div className="flex items-center justify-center gap-1.5">
      <span className="text-sm">{directCount}×</span>
      {hasLineHistory && (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger>
              <Layers className="h-3.5 w-3.5 text-blue-500" />
            </TooltipTrigger>
            <TooltipContent side="left" className="max-w-[220px]">
              <p className="text-xs font-medium">Line: {p.line}</p>
              <p className="text-xs text-muted-foreground">
                {p.line_products_featured} of {p.line_product_count} products featured
                ({p.line_products_featured_30d} in last 30d)
              </p>
              <p className="text-xs text-muted-foreground">
                Line last featured {p.line_days_since_featured}d ago
              </p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      )}
    </div>
  )
}

function LastFeaturedCell({ p }: { p: Product }) {
  if (p.last_featured_at) {
    return <span>{p.days_since_featured === 0 ? "Today" : `${p.days_since_featured}d ago`}</span>
  }
  if (p.line_last_featured_at) {
    const lineLabel = p.line_days_since_featured === 0 ? "Today" : `${p.line_days_since_featured}d ago`
    return (
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger className="flex items-center justify-center gap-1 text-blue-500">
            <Layers className="h-3 w-3" />
            <span>{lineLabel}</span>
          </TooltipTrigger>
          <TooltipContent side="left">
            <p className="text-xs">Product never featured directly.</p>
            <p className="text-xs">Line "{p.line}" was last featured {lineLabel.toLowerCase()}.</p>
          </TooltipContent>
        </Tooltip>
      </TooltipProvider>
    )
  }
  return <span>Never</span>
}
function CopyPidButton({ pid }: { pid: number }) {
  const [copied, setCopied] = useState(false)
  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => {
              navigator.clipboard.writeText(String(pid))
              toast.success(`Copied PID ${pid}`)
              setCopied(true)
              setTimeout(() => setCopied(false), 1500)
            }}
          >
            {copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <p className="text-xs">{copied ? "Copied!" : "Copy product ID"}</p>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  )
}

interface ScoreBreakdown {
  new_boost: number; preorder_boost: number; clearance_boost: number
  velocity_boost: number; back_in_stock_boost: number; interest_boost: number
  recency_adj: number; over_featured_adj: number; line_saturation_adj: number
  price_tier_adj: number; abc_boost: number; stock_penalty: number
}

const SCORE_LABELS: Record<keyof ScoreBreakdown, string> = {
  new_boost: "New Product", preorder_boost: "Pre-Order", clearance_boost: "Clearance",
  velocity_boost: "Sales Velocity", back_in_stock_boost: "Back in Stock", interest_boost: "Interest",
  recency_adj: "Recency", over_featured_adj: "Over-Featured", line_saturation_adj: "Line Saturation",
  price_tier_adj: "Price Tier", abc_boost: "ABC Class", stock_penalty: "Stock"
}

function ScoreBreakdownTooltip({ pid, score, children }: { pid: number; score: number; children: React.ReactNode }) {
  const [hovered, setHovered] = useState(false)
  const { data } = useQuery<ScoreBreakdown>({
    queryKey: ["score-breakdown", pid],
    queryFn: async () => {
      const res = await apiFetch(`${config.apiUrl}/newsletter/score-breakdown/${pid}`)
      if (!res.ok) throw new Error("Failed")
      return res.json()
    },
    enabled: hovered,
    staleTime: 60_000,
  })

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild onMouseEnter={() => setHovered(true)}>
          {children}
        </TooltipTrigger>
        <TooltipContent side="right" className="p-0">
          <div className="p-2 min-w-[180px]">
            <p className="text-xs font-semibold mb-1.5 border-b pb-1">Score Breakdown: {score}</p>
            {data ? (
              <div className="space-y-0.5">
                {(Object.keys(SCORE_LABELS) as (keyof ScoreBreakdown)[]).map(k => {
                  const v = Number(data[k])
                  if (v === 0) return null
                  return (
                    <div key={k} className="flex justify-between text-xs gap-4">
                      <span className="text-muted-foreground">{SCORE_LABELS[k]}</span>
                      <span className={v > 0 ? "text-green-600" : "text-red-500"}>{v > 0 ? "+" : ""}{v}</span>
                    </div>
                  )
                })}
              </div>
            ) : (
              <p className="text-xs text-muted-foreground">Loading…</p>
            )}
          </div>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  )
}

type SortColumn = "score" | "brand" | "price" | "stock" | "sales_7d" | "sales_30d" | "times_featured" | "days_since_featured"
type SortDirection = "asc" | "desc" | null
interface SortState { column: SortColumn | null; direction: SortDirection }

function toggleSort(prev: SortState, column: SortColumn): SortState {
  if (prev.column !== column) return { column, direction: "asc" }
  if (prev.direction === "asc") return { column, direction: "desc" }
  return { column: null, direction: null }
}

function SortableHeader({ label, column, sort, onSort, className }: {
  label: string; column: SortColumn; sort: SortState; onSort: (c: SortColumn) => void; className?: string
}) {
  const active = sort.column === column
  return (
    <TableHead className={`${className ?? ""} cursor-pointer select-none`} onClick={() => onSort(column)}>
      <div className={`flex items-center gap-1 ${className?.includes("text-right") ? "justify-end" : className?.includes("text-center") ? "justify-center" : ""}`}>
        <span>{label}</span>
        {active && sort.direction === "asc" ? <ArrowUp className="h-3 w-3" /> :
         active && sort.direction === "desc" ? <ArrowDown className="h-3 w-3" /> :
         <ArrowUpDown className="h-3 w-3 opacity-30" />}
      </div>
    </TableHead>
  )
}

export function RecommendationTable({ category }: RecommendationTableProps) {
  const { user } = useContext(AuthContext)
  const canDebug = user?.is_admin || user?.permissions?.includes("admin:debug")
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState<SortState>({ column: null, direction: null })
  const limit = 100

  const { data, isLoading } = useQuery<RecommendationResponse>({
    queryKey: ["newsletter-recommendations", category, page],
    queryFn: async () => {
      const res = await apiFetch(
        `${config.apiUrl}/newsletter/recommendations?category=${category}&page=${page}&limit=${limit}`
      )
      if (!res.ok) throw new Error("Failed to fetch recommendations")
      return res.json()
    },
  })

  const products = useMemo(() => {
    const list = data?.products ?? []
    if (!sort.column || !sort.direction) return list
    const col = sort.column
    const dir = sort.direction === "asc" ? 1 : -1
    return [...list].sort((a, b) => {
      let av: number, bv: number
      switch (col) {
        case "score": av = a.score; bv = b.score; break
        case "brand": return dir * (a.brand ?? "").localeCompare(b.brand ?? "")
        case "price": av = Number(a.is_daily_deal && a.deal_price ? a.deal_price : a.price); bv = Number(b.is_daily_deal && b.deal_price ? b.deal_price : b.price); break
        case "stock": av = a.current_stock ?? 0; bv = b.current_stock ?? 0; break
        case "sales_7d": av = a.sales_7d ?? 0; bv = b.sales_7d ?? 0; break
        case "sales_30d": av = a.sales_30d ?? 0; bv = b.sales_30d ?? 0; break
        case "times_featured": av = a.times_featured ?? 0; bv = b.times_featured ?? 0; break
        case "days_since_featured": av = a.effective_days_since_featured ?? 9999; bv = b.effective_days_since_featured ?? 9999; break
        default: return 0
      }
      return dir * (av - bv)
    })
  }, [data?.products, sort.column, sort.direction])
  const pagination = data?.pagination

  if (isLoading) {
    return <div className="text-center py-12 text-muted-foreground">Loading recommendations…</div>
  }

  return (
    <div>
      <div className="rounded-md border overflow-x-auto">
        <Table className="">
          <TableHeader>
            <TableRow>
              <SortableHeader label="Score" column="score" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} className="w-[50px]" />
              <TableHead className="w-[60px]">Image</TableHead>
              <TableHead>Product</TableHead>
              <SortableHeader label="Brand" column="brand" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} />
              <SortableHeader label="Price" column="price" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} className="text-center" />
              <SortableHeader label="Stock" column="stock" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} className="text-center" />
              <SortableHeader label="7d Sales" column="sales_7d" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} className="text-center" />
              <SortableHeader label="30d Sales" column="sales_30d" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} className="text-center" />
              <TableHead>Tags</TableHead>
              <SortableHeader label="Featured" column="times_featured" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} className="text-center" />
              <SortableHeader label="Last Featured" column="days_since_featured" sort={sort} onSort={(c) => setSort(toggleSort(sort, c))} />
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {products.length === 0 ? (
              <TableRow>
                <TableCell colSpan={12} className="text-center py-8 text-muted-foreground">
                  No products found for this category
                </TableCell>
              </TableRow>
            ) : (
              products.map((p) => (
                <TableRow key={p.pid}>
                  <TableCell>
                    {canDebug ? (
                      <ScoreBreakdownTooltip pid={p.pid} score={p.score}>
                        <span className={`font-mono font-bold text-sm cursor-help ${
                          p.score >= 40 ? "text-green-600" :
                          p.score >= 20 ? "text-yellow-600" :
                          "text-muted-foreground"
                        }`}>
                          {p.score}
                        </span>
                      </ScoreBreakdownTooltip>
                    ) : (
                      <span className={`font-mono font-bold text-sm ${
                        p.score >= 40 ? "text-green-600" :
                        p.score >= 20 ? "text-yellow-600" :
                        "text-muted-foreground"
                      }`}>
                        {p.score}
                      </span>
                    )}
                  </TableCell>
                  <TableCell>
                    {p.image ? (
                      <img src={p.image} alt="" className="w-10 h-10 object-cover rounded" />
                    ) : (
                      <div className="w-10 h-10 bg-muted rounded" />
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="max-w-[400px]">
                      <p className="font-medium text-sm line-clamp-2">{p.title}</p>
                      {p.line && (
                        <p className="text-[10px] text-muted-foreground/70 truncate">{p.line}</p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">{p.brand}</TableCell>
                  <TableCell className="text-center">
                    <div>
                      {p.is_daily_deal && p.deal_price ? (
                        <>
                          <span className="text-sm font-medium">${Number(p.deal_price).toFixed(2)}</span>
                          <div>
                            <span className="text-xs text-muted-foreground line-through">
                              ${Number(p.price).toFixed(2)}
                            </span>
                            <span className="text-xs text-red-500 ml-1">
                              -{Math.round((1 - Number(p.deal_price) / Number(p.price)) * 100)}%
                            </span>
                          </div>
                        </>
                      ) : (
                        <>
                          <span className="text-sm font-medium">${Number(p.price).toFixed(2)}</span>
                          {p.is_clearance && (
                            <div>
                              <span className="text-xs text-muted-foreground line-through">
                                ${Number(p.regular_price).toFixed(2)}
                              </span>
                              <span className="text-xs text-red-500 ml-1">-{p.discount_pct}%</span>
                            </div>
                          )}
                        </>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <span className={`text-sm ${p.current_stock <= 0 ? "text-red-500" : p.is_low_stock ? "text-yellow-600" : ""}`}>
                      {p.current_stock ?? 0}
                    </span>
                    {p.preorder_count > 0 && (
                      <span className="text-xs text-blue-500 ml-1">(+{p.preorder_count})</span>
                    )}
                  </TableCell>
                  <TableCell className="text-center text-sm">{p.sales_7d ?? 0}</TableCell>
                  <TableCell className="text-center text-sm">{p.sales_30d ?? 0}</TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {p.is_new && <Badge variant="default" className="text-[10px] px-1.5 py-0 whitespace-nowrap">New</Badge>}
                      {p.is_preorder && <Badge variant="secondary" className="text-[10px] px-1.5 py-0 whitespace-nowrap">Pre-Order</Badge>}
                      {p.is_clearance && <Badge variant="destructive" className="text-[10px] px-1.5 py-0 whitespace-nowrap">Clearance</Badge>}
                      {p.is_daily_deal && <Badge variant="destructive" className="text-[10px] px-1.5 py-0 bg-orange-500">Deal</Badge>}
                      {p.is_back_in_stock && <Badge variant="outline" className="text-[10px] px-1.5 py-0 whitespace-nowrap">Back in Stock</Badge>}
                      {p.is_low_stock && <Badge variant="outline" className="text-[10px] px-1.5 py-0 border-yellow-500 whitespace-nowrap">Low Stock</Badge>}
                      {(p.baskets > 0 || p.notifies > 0) && (
                        <Badge variant="outline" className="text-[10px] px-1.5 py-0 border-purple-500">
                          {p.baskets > 0 ? `${p.baskets} 🛒` : ""}{p.baskets > 0 && p.notifies > 0 ? " " : ""}{p.notifies > 0 ? `${p.notifies} 🔔` : ""}
                        </Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-center text-sm">
                    <FeaturedCell p={p} />
                  </TableCell>
                  <TableCell className="text-center text-sm text-muted-foreground">
                    <LastFeaturedCell p={p} />
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <CopyPidButton pid={p.pid} />
                      {p.permalink && (
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                variant="ghost"
                                size="icon"
                                asChild
                              >
                                <a href={p.permalink} target="_blank" rel="noopener noreferrer">
                                  <ExternalLink className="h-4 w-4" />
                                </a>
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>
                              Open in shop
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {pagination && pagination.pages > 1 && (
        <div className="flex items-center justify-between mt-4">
          <p className="text-sm text-muted-foreground">
            {pagination.total.toLocaleString()} products
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline" size="sm"
              disabled={page <= 1}
              onClick={() => setPage(page - 1)}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm">
              Page {page} of {pagination.pages}
            </span>
            <Button
              variant="outline" size="sm"
              disabled={page >= pagination.pages}
              onClick={() => setPage(page + 1)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
