"use client"

import { useEffect, useState } from "react"
import {
  TrendingUp,
  ShoppingBag,
  DollarSign,
  Users,
  ArrowUpRight,
  Sparkles,
  Calendar,
  Layers,
  ChevronRight,
  Loader2,
  Package,
} from "lucide-react"
import Link from "next/link"
import api from "@/lib/axios"

export default function AdminDashboardPage() {
  const [timeframe, setTimeframe] = useState<"weekly" | "monthly">("weekly")
  const [stats, setStats] = useState<any>(null)
  const [showcaseProducts, setShowcaseProducts] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchDashboardStats() {
      try {
        const [dashboardRes, productsRes] = await Promise.all([
          api.get("/admin/dashboard"),
          api.get("/admin/products?limit=3")
        ])
        setStats(dashboardRes.data)
        setShowcaseProducts(productsRes.data.data || productsRes.data)
      } catch (err) {
        console.error("Failed to load dashboard statistics:", err)
      } finally {
        setLoading(false)
      }
    }
    fetchDashboardStats()
  }, [])

  if (loading || !stats) {
    return (
      <div className="flex h-96 items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-indigo-500" />
      </div>
    )
  }

  const {
    totalRevenue,
    activeOrdersCount,
    totalClients,
    recentRevenue,
    previousRevenue,
    recentOrders,
    previousOrders,
    recentTransactions,
    chartOrders
  } = stats

  // Dynamic growth calculations
  const revGrowth = previousRevenue === 0 ? (recentRevenue > 0 ? 100 : 0) : ((recentRevenue - previousRevenue) / previousRevenue) * 100
  const ordersGrowth = previousOrders === 0 ? (recentOrders > 0 ? 100 : 0) : ((recentOrders - previousOrders) / previousOrders) * 100

  // We skip client growth and AOV growth for brevity, or set to a rough metric based on DB stats.
  const clientsGrowth = ordersGrowth // Approximation
  
  const currentAov = recentOrders > 0 ? recentRevenue / recentOrders : 0
  const previousAov = previousOrders > 0 ? previousRevenue / previousOrders : 0
  const aovGrowth = previousAov === 0 ? (currentAov > 0 ? 100 : 0) : ((currentAov - previousAov) / previousAov) * 100

  // Dynamic revenue chart coordinates
  const today = new Date()
  today.setHours(23, 59, 59, 999)
  
  const dynamicWeeklyData = Array(7).fill(0)
  chartOrders.forEach((o: any) => {
    const orderDate = new Date(o.createdAt)
    const diffTime = today.getTime() - orderDate.getTime()
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
    if (diffDays >= 0 && diffDays < 7) {
      const index = 6 - diffDays
      dynamicWeeklyData[index] += o.totalAmount
    }
  })

  const dynamicMonthlyData = Array(12).fill(0)
  const currentYear = today.getFullYear()
  chartOrders.forEach((o: any) => {
    const orderDate = new Date(o.createdAt)
    if (orderDate.getFullYear() === currentYear) {
      dynamicMonthlyData[orderDate.getMonth()] += o.totalAmount
    }
  })

  // Prevent SVG division by zero if no data
  const safeWeeklyData = dynamicWeeklyData.every(v => v === 0) ? [10, 10, 10, 10, 10, 10, 10] : dynamicWeeklyData
  const safeMonthlyData = dynamicMonthlyData.every(v => v === 0) ? Array(12).fill(10) : dynamicMonthlyData

  const chartPoints = timeframe === "weekly" ? safeWeeklyData : safeMonthlyData
  const maxVal = Math.max(...chartPoints)
  const height = 240
  const width = 800

  // Generate SVG Path
  const points = chartPoints.map((val, index) => {
    const x = (index / (chartPoints.length - 1)) * width
    const y = height - (val / maxVal) * (height - 40) - 20
    return `${x},${y}`
  })
  
  const pathData = `M ${points.join(" L ")}`
  const areaData = `${pathData} L ${width},${height} L 0,${height} Z`

  return (
    <div className="space-y-6 max-w-7xl mx-auto p-2">
      {/* LUXURY GREETING HEADER */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-gradient-to-r from-zinc-950 via-indigo-950 to-zinc-950 text-white rounded-2xl p-6 shadow-2xl relative overflow-hidden border border-indigo-500/20">
        <div className="absolute top-0 right-0 w-64 h-64 bg-violet-500/15 rounded-full blur-3xl -mr-12 -mt-12 pointer-events-none" />
        <div className="absolute bottom-0 left-0 w-64 h-64 bg-emerald-500/10 rounded-full blur-3xl -ml-12 -mb-12 pointer-events-none" />
        
        <div className="relative z-10 space-y-2">
          <div className="flex items-center gap-2">
            <span className="bg-gradient-to-r from-violet-500/20 to-indigo-500/20 text-indigo-300 text-[10px] px-3 py-1 rounded-full font-bold uppercase tracking-wider flex items-center gap-1.5 backdrop-blur-md border border-indigo-400/20">
              <Sparkles className="w-3 h-3 text-cyan-400 animate-spin" style={{ animationDuration: '4s' }} />
              Live Workspace Status
            </span>
          </div>
          <h1 className="text-3xl md:text-4xl font-black tracking-tight leading-none bg-gradient-to-r from-white via-zinc-100 to-zinc-400 bg-clip-text text-transparent">
            Greetings, Creative Curator
          </h1>
          <p className="text-zinc-400 text-xs max-w-md font-medium leading-relaxed">
            Your high-end luxury e-commerce suite is humming. Performance metrics are trending upward.
          </p>
        </div>

        <div className="flex items-center gap-4 relative z-10 shrink-0">
          <div className="flex items-center gap-3 bg-white/5 backdrop-blur-md border border-white/10 rounded-xl p-3.5 text-zinc-300 shadow-inner">
            <Calendar className="w-5 h-5 text-cyan-400" />
            <div className="text-left">
              <p className="text-[9px] text-zinc-500 font-extrabold uppercase tracking-widest">Server Time</p>
              <p className="text-xs font-black font-mono tracking-wide text-white">
                {new Date().toLocaleDateString("en-US", { dateStyle: "medium" })}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* METRICS ROW */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* REVENUE CARD */}
        <div className="group bg-white rounded-2xl border border-zinc-100/80 p-5 shadow-sm hover:shadow-xl hover:shadow-emerald-500/10 hover:border-emerald-200 hover:-translate-y-0.5 transition-all duration-300 flex flex-col justify-between relative overflow-hidden">
          <div className="absolute top-0 right-0 w-20 h-20 bg-emerald-500/5 rounded-full blur-2xl group-hover:scale-150 transition duration-500" />
          <div className="flex justify-between items-start">
            <div className="p-3 bg-emerald-50 text-emerald-600 rounded-xl group-hover:bg-emerald-500 group-hover:text-white group-hover:shadow-md group-hover:shadow-emerald-500/20 transition-all duration-300">
              <DollarSign className="w-5 h-5" />
            </div>
            <span className="flex items-center gap-1 text-[10px] font-bold text-emerald-600 bg-emerald-50/80 px-2 py-0.5 rounded-full border border-emerald-100">
              <ArrowUpRight className="w-3 h-3" />
              {revGrowth >= 0 ? "+" : ""}{revGrowth.toFixed(1)}%
            </span>
          </div>
          <div className="mt-4">
            <p className="text-[9px] font-extrabold text-zinc-400 uppercase tracking-widest">Gross Revenue</p>
            {loading ? (
              <Loader2 className="w-5 h-5 animate-spin text-zinc-400 mt-2" />
            ) : (
              <h3 className="text-2xl font-black text-zinc-950 mt-1 font-mono tracking-tight group-hover:text-emerald-600 transition">
                ${totalRevenue.toLocaleString()}
              </h3>
            )}
          </div>
        </div>

        {/* ORDERS CARD */}
        <div className="group bg-white rounded-2xl border border-zinc-100/80 p-5 shadow-sm hover:shadow-xl hover:shadow-indigo-500/10 hover:border-indigo-200 hover:-translate-y-0.5 transition-all duration-300 flex flex-col justify-between relative overflow-hidden">
          <div className="absolute top-0 right-0 w-20 h-20 bg-indigo-500/5 rounded-full blur-2xl group-hover:scale-150 transition duration-500" />
          <div className="flex justify-between items-start">
            <div className="p-3 bg-indigo-50 text-indigo-600 rounded-xl group-hover:bg-indigo-500 group-hover:text-white group-hover:shadow-md group-hover:shadow-indigo-500/20 transition-all duration-300">
              <ShoppingBag className="w-5 h-5" />
            </div>
            <span className="flex items-center gap-1 text-[10px] font-bold text-indigo-600 bg-indigo-50/80 px-2 py-0.5 rounded-full border border-indigo-100">
              <ArrowUpRight className="w-3 h-3" />
              {ordersGrowth >= 0 ? "+" : ""}{ordersGrowth.toFixed(1)}%
            </span>
          </div>
          <div className="mt-4">
            <p className="text-[9px] font-extrabold text-zinc-400 uppercase tracking-widest">Active Pipeline</p>
            {loading ? (
              <Loader2 className="w-5 h-5 animate-spin text-zinc-400 mt-2" />
            ) : (
              <h3 className="text-2xl font-black text-zinc-950 mt-1 font-mono tracking-tight group-hover:text-indigo-600 transition">
                {activeOrdersCount} {activeOrdersCount === 1 ? "Order" : "Orders"}
              </h3>
            )}
          </div>
        </div>

        {/* CUSTOMERS CARD */}
        <div className="group bg-white rounded-2xl border border-zinc-100/80 p-5 shadow-sm hover:shadow-xl hover:shadow-purple-500/10 hover:border-purple-200 hover:-translate-y-0.5 transition-all duration-300 flex flex-col justify-between relative overflow-hidden">
          <div className="absolute top-0 right-0 w-20 h-20 bg-purple-500/5 rounded-full blur-2xl group-hover:scale-150 transition duration-500" />
          <div className="flex justify-between items-start">
            <div className="p-3 bg-purple-50 text-purple-600 rounded-xl group-hover:bg-purple-500 group-hover:text-white group-hover:shadow-md group-hover:shadow-purple-500/20 transition-all duration-300">
              <Users className="w-5 h-5" />
            </div>
            <span className="flex items-center gap-1 text-[10px] font-bold text-purple-600 bg-purple-50/80 px-2 py-0.5 rounded-full border border-purple-100">
              <ArrowUpRight className="w-3 h-3" />
              {clientsGrowth >= 0 ? "+" : ""}{clientsGrowth.toFixed(1)}%
            </span>
          </div>
          <div className="mt-4">
            <p className="text-[9px] font-extrabold text-zinc-400 uppercase tracking-widest">Curated Clientele</p>
            {loading ? (
              <Loader2 className="w-5 h-5 animate-spin text-zinc-400 mt-2" />
            ) : (
              <h3 className="text-2xl font-black text-zinc-950 mt-1 font-mono tracking-tight group-hover:text-purple-600 transition">
                {totalClients} {totalClients === 1 ? "Client" : "Clients"}
              </h3>
            )}
          </div>
        </div>

        {/* CONVERSION CARD */}
        <div className="group bg-white rounded-2xl border border-zinc-100/80 p-5 shadow-sm hover:shadow-xl hover:shadow-rose-500/10 hover:border-rose-200 hover:-translate-y-0.5 transition-all duration-300 flex flex-col justify-between relative overflow-hidden">
          <div className="absolute top-0 right-0 w-20 h-20 bg-rose-500/5 rounded-full blur-2xl group-hover:scale-150 transition duration-500" />
          <div className="flex justify-between items-start">
            <div className="p-3 bg-rose-50 text-rose-600 rounded-xl group-hover:bg-rose-500 group-hover:text-white group-hover:shadow-md group-hover:shadow-rose-500/20 transition-all duration-300">
              <TrendingUp className="w-5 h-5" />
            </div>
            <span className="flex items-center gap-1 text-[10px] font-bold text-rose-600 bg-rose-50/80 px-2 py-0.5 rounded-full border border-rose-100">
              <ArrowUpRight className="w-3 h-3" />
              {aovGrowth >= 0 ? "+" : ""}{aovGrowth.toFixed(1)}%
            </span>
          </div>
          <div className="mt-4">
            <p className="text-[9px] font-extrabold text-zinc-400 uppercase tracking-widest">Avg Order Value</p>
            {loading ? (
              <Loader2 className="w-5 h-5 animate-spin text-zinc-400 mt-2" />
            ) : (
              <h3 className="text-2xl font-black text-zinc-950 mt-1 font-mono tracking-tight group-hover:text-rose-600 transition">
                ${currentAov.toFixed(2)}
              </h3>
            )}
          </div>
        </div>
      </div>

      {/* GRAPH CHART CONTAINER */}
      <div className="bg-white rounded-2xl border border-zinc-100 p-6 shadow-sm hover:shadow-xl hover:shadow-indigo-500/5 transition-all duration-500 relative">
        <div className="absolute top-0 right-0 w-72 h-72 bg-indigo-500/5 rounded-full blur-3xl pointer-events-none" />
        
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6 relative z-10">
          <div>
            <h3 className="text-lg font-black text-zinc-950 tracking-tight flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-indigo-600" />
              Revenue Trend Tracker
            </h3>
            <p className="text-[10px] text-zinc-500 mt-0.5">Live vector feed tracking retail checkouts and pipeline volumes.</p>
          </div>
          
          {/* Timeframe Selector Button Group */}
          <div className="flex bg-zinc-100 p-1 rounded-xl border border-zinc-200/60 shrink-0">
            <button
              onClick={() => setTimeframe("weekly")}
              className={`px-4 py-2 rounded-lg text-[10px] font-bold transition-all duration-300 cursor-pointer ${
                timeframe === "weekly"
                  ? "bg-gradient-to-r from-violet-600 to-indigo-600 text-white shadow-md shadow-indigo-600/20"
                  : "text-zinc-500 hover:text-zinc-950"
              }`}
            >
              Weekly Analytics
            </button>
            <button
              onClick={() => setTimeframe("monthly")}
              className={`px-4 py-2 rounded-lg text-[10px] font-bold transition-all duration-300 cursor-pointer ${
                timeframe === "monthly"
                  ? "bg-gradient-to-r from-violet-600 to-indigo-600 text-white shadow-md shadow-indigo-600/20"
                  : "text-zinc-500 hover:text-zinc-950"
              }`}
            >
              Monthly Forecast
            </button>
          </div>
        </div>

        {/* SVG VECTOR CHART */}
        <div className="relative w-full overflow-hidden z-10">
          <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-auto overflow-visible select-none">
            <defs>
              <linearGradient id="gradient-area" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#8b5cf6" stopOpacity="0.22" />
                <stop offset="100%" stopColor="#4f46e5" stopOpacity="0.00" />
              </linearGradient>
              <linearGradient id="gradient-stroke" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#8b5cf6" />
                <stop offset="50%" stopColor="#6366f1" />
                <stop offset="100%" stopColor="#06b6d4" />
              </linearGradient>
            </defs>

            {/* Grid Lines */}
            <line x1="0" y1="20" x2={width} y2="20" stroke="#f4f4f5" strokeWidth="1" strokeDasharray="4" />
            <line x1="0" y1={height / 2} x2={width} y2={height / 2} stroke="#f4f4f5" strokeWidth="1" strokeDasharray="4" />
            <line x1="0" y1={height - 20} x2={width} y2={height - 20} stroke="#f4f4f5" strokeWidth="1" strokeDasharray="4" />

            {/* Area Path */}
            <path d={areaData} fill="url(#gradient-area)" className="transition-all duration-700 ease-in-out" />

            {/* Line Path */}
            <path
              d={pathData}
              fill="none"
              stroke="url(#gradient-stroke)"
              strokeWidth="4"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="transition-all duration-700 ease-in-out"
            />

            {/* Visual Point Anchors */}
            {points.map((pt, idx) => {
              const [x, y] = pt.split(",")
              return (
                <g key={idx} className="group/point">
                  <circle
                    cx={x}
                    cy={y}
                    r="8"
                    className="fill-indigo-500 opacity-0 group-hover/point:opacity-30 group-hover/point:scale-150 transition-all duration-300 cursor-pointer"
                  />
                  <circle
                    cx={x}
                    cy={y}
                    r="4.5"
                    className="fill-white stroke-indigo-600 stroke-3 transition duration-300 group-hover/point:r-5.5 cursor-pointer"
                  />
                </g>
              )
            })}
          </svg>
        </div>
      </div>

      {/* LOWER SPLIT DETAILS PANEL */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* INVENTORY FOCUS CARD */}
        <div className="bg-white rounded-2xl border border-zinc-100 p-6 shadow-sm hover:shadow-xl hover:shadow-indigo-500/5 transition-all duration-500 flex flex-col justify-between">
          <div>
            <h3 className="text-base font-black text-zinc-950 flex items-center gap-2 mb-5">
              <span className="w-2 h-2 rounded-full bg-violet-600 animate-ping" />
              Luxury Performance Showcase
            </h3>

            <div className="divide-y divide-zinc-100">
              {loading ? (
                <div className="py-8 flex justify-center"><Loader2 className="w-5 h-5 animate-spin text-zinc-400" /></div>
              ) : showcaseProducts.length === 0 ? (
                <div className="py-8 text-center text-zinc-400 text-xs font-semibold">No products found</div>
              ) : (
                showcaseProducts.map(product => (
                  <div key={product.id} className="py-4.5 flex items-center justify-between group cursor-pointer">
                    <div className="flex items-center gap-4.5">
                      <div className="w-14 h-14 rounded-2xl bg-zinc-50 border overflow-hidden shrink-0 flex items-center justify-center shadow-inner group-hover:border-violet-300 transition duration-300">
                        {product.thumbnail ? (
                          <img
                            src={product.thumbnail}
                            className="w-full h-full object-cover group-hover:scale-105 transition duration-300"
                            alt={product.title}
                          />
                        ) : (
                          <Package className="w-6 h-6 text-zinc-300" />
                        )}
                      </div>
                      <div>
                        <h4 className="font-bold text-zinc-950 text-sm group-hover:text-indigo-600 transition truncate w-32 md:w-48">{product.title}</h4>
                        <p className="text-[10px] font-semibold text-zinc-400 uppercase tracking-wider mt-0.5">Category: {product.category?.name || "Uncategorized"}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <span className="text-sm font-black text-zinc-900 font-mono">${(product.basePrice || 0).toLocaleString()}</span>
                      <p className="text-[9px] font-extrabold text-zinc-400 uppercase tracking-widest mt-0.5">
                        {product.variants?.reduce((sum: number, v: any) => sum + (v.stock || 0), 0) || 0} in stock
                      </p>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
          
          <Link href="/admin/products" className="block w-full">
            <button className="w-full bg-zinc-50 border border-zinc-200/60 hover:bg-zinc-900 hover:text-white hover:border-transparent text-zinc-600 font-bold py-3 rounded-xl transition duration-300 mt-4 text-[9px] tracking-widest uppercase flex items-center justify-center gap-1.5 cursor-pointer shadow-sm">
              Manage Complete Inventory
              <ChevronRight className="w-3.5 h-3.5" />
            </button>
          </Link>
        </div>

        {/* RECENT TRANSACTIONS */}
        <div className="bg-white rounded-2xl border border-zinc-100 p-6 shadow-sm hover:shadow-xl hover:shadow-purple-500/5 transition-all duration-500 flex flex-col justify-between">
          <div>
            <h3 className="text-base font-black text-zinc-950 flex items-center gap-2 mb-5">
              <Layers className="text-purple-500 w-4.5 h-4.5 animate-pulse" />
              Sleek Transaction Feed
            </h3>

            {loading ? (
              <div className="flex flex-col items-center justify-center py-10">
                <Loader2 className="w-6 h-6 animate-spin text-zinc-400 mb-2" />
                <span className="text-[10px] text-zinc-400 font-semibold">Loading feed...</span>
              </div>
            ) : recentTransactions.length === 0 ? (
              <div className="text-center py-12 flex flex-col items-center justify-center">
                <Package className="text-zinc-300 w-8 h-8 mb-2" />
                <p className="text-zinc-400 text-xs font-semibold">No recent transactions recorded</p>
              </div>
            ) : (
              <div className="space-y-4">
                {recentTransactions.map((tx: any) => {
                  const itemsSummary = (tx.items || [])
                    .map((i: any) => `${i.quantity}x ${i.variant?.product?.title || 'Unknown Item'}`)
                    .join(", ")

                  return (
                    <div key={tx.id} className="flex gap-4 group">
                      <div className="w-10 h-10 rounded-full bg-indigo-50 border border-indigo-100/50 flex items-center justify-center shrink-0 group-hover:scale-110 duration-300">
                        <Users className="w-4 h-4 text-indigo-600" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center justify-between">
                          <p className="text-sm font-bold text-zinc-950 truncate group-hover:text-indigo-600 transition">
                            {tx.user?.name || "Guest Customer"}
                          </p>
                          <span className="text-xs font-black text-emerald-600 font-mono">
                            +${tx.totalAmount.toLocaleString()}
                          </span>
                        </div>
                        <p className="text-xs text-zinc-400 mt-0.5 truncate">{itemsSummary}</p>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>

          <Link href="/admin/orders" className="block w-full">
            <button className="w-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white font-bold py-3 rounded-xl hover:opacity-90 transition mt-6 text-[9px] tracking-widest uppercase flex items-center justify-center gap-1.5 cursor-pointer shadow-lg shadow-indigo-600/30">
              View All Orders
              <ArrowUpRight className="w-4 h-4" />
            </button>
          </Link>
        </div>
      </div>
    </div>
  )
}