"use client"

import { useState, useEffect } from "react"
import {
  Boxes,
  AlertTriangle,
  Check,
  Edit2,
  Search,
  RefreshCw,
  Plus,
  Minus,
  Loader2,
  TrendingDown,
  DollarSign,
  PackageCheck
} from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

type VariantItem = {
  id: string
  productId: string
  productName: string
  productImage: string
  productCategory: string
  sku: string
  color: string
  size: string
  length: string | null
  stock: number
  price: number
}

export default function InventoryPage() {
  const [search, setSearch] = useState("")
  const [stockFilter, setStockFilter] = useState("all") // 'all', 'low', 'out', 'in'
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 10

  const [editingId, setEditingId] = useState<string | null>(null)
  const [tempStock, setTempStock] = useState<number>(0)

  const [loading, setLoading] = useState(true)
  const [variants, setVariants] = useState<VariantItem[]>([])
  const [saving, setSaving] = useState(false)

  // Reset page when filters change
  useEffect(() => {
    setCurrentPage(1)
  }, [search, stockFilter])

  // Fetch all products and flatten their variants
  async function fetchInventory() {
    try {
      setLoading(true)
      const res = await api.get("/admin/products?limit=1000")
      const products = res.data.data || res.data

      const flattenedVariants: VariantItem[] = []
      
      products.forEach((product: any) => {
        if (product.variants) {
          product.variants.forEach((v: any) => {
            flattenedVariants.push({
              id: v.id,
              productId: product.id,
              productName: product.title,
              productImage: product.thumbnail,
              productCategory: product.category?.name || "Uncategorized",
              sku: v.sku || `SKU-${product.id.slice(-4)}-${v.color.slice(0,2)}-${v.size}`,
              color: v.color,
              size: v.size,
              length: v.length,
              stock: v.stock,
              price: product.basePrice,
            })
          })
        }
      })
      
      setVariants(flattenedVariants)
    } catch (error) {
      console.error("Failed to load inventory:", error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchInventory()
  }, [])

  // Filter list
  const filteredInventory = variants.filter((item) => {
    const matchesSearch = 
      item.productName.toLowerCase().includes(search.toLowerCase()) ||
      item.sku.toLowerCase().includes(search.toLowerCase()) ||
      item.color.toLowerCase().includes(search.toLowerCase())

    let matchesStock = true
    if (stockFilter === "low") matchesStock = item.stock <= 5 && item.stock > 0
    else if (stockFilter === "out") matchesStock = item.stock === 0
    else if (stockFilter === "in") matchesStock = item.stock > 5

    return matchesSearch && matchesStock
  })

  // Pagination Logic
  const totalPages = Math.ceil(filteredInventory.length / itemsPerPage)
  const paginatedInventory = filteredInventory.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  )

  // Start inline editing
  function startEditing(item: VariantItem) {
    setEditingId(item.id)
    setTempStock(item.stock)
  }

  // Save stock change
  async function saveStockChange(id: string) {
    try {
      setSaving(true)
      await api.patch(`/admin/variants/${id}`, { stock: tempStock })
      
      setVariants((prev) =>
        prev.map((item) =>
          item.id === id ? { ...item, stock: tempStock } : item
        )
      )
      setEditingId(null)
    } catch (error) {
      console.error("Failed to update stock", error)
      Swal.fire({ text: "Failed to update stock in database.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setSaving(false)
    }
  }

  // Statistics
  const totalItems = variants.reduce((sum, v) => sum + v.stock, 0)
  const lowStockItems = variants.filter((item) => item.stock <= 5)
  const totalValue = variants.reduce((sum, v) => sum + (v.stock * v.price), 0)

  return (
    <div className="space-y-8 max-w-[1600px] mx-auto pb-10">
      {/* HEADER SECTION */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2.5 bg-zinc-950 text-white rounded-2xl shadow-xl shadow-zinc-900/20">
              <Boxes size={22} />
            </div>
            <h1 className="text-3xl font-black tracking-tight text-zinc-900">
              Inventory Matrix
            </h1>
          </div>
          <p className="text-zinc-500 text-xs max-w-md font-medium">
            Live database view of all product variants, SKU tracking, and real-time stock valuation.
          </p>
        </div>

        <button 
          onClick={fetchInventory}
          className="flex items-center gap-2 px-5 py-3 bg-white hover:bg-zinc-50 hover:shadow-md border border-zinc-200 text-zinc-700 font-bold rounded-xl transition-all cursor-pointer shadow-sm text-xs uppercase tracking-wider shrink-0"
        >
          <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
          Sync Database
        </button>
      </div>

      {/* INTELLIGENT SUMMARY CARDS */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-gradient-to-br from-white to-zinc-50 border border-zinc-200 rounded-3xl p-6 flex flex-col justify-between shadow-sm relative overflow-hidden">
          <div className="absolute -right-4 -top-4 text-emerald-500/5">
            <PackageCheck size={120} />
          </div>
          <div className="flex items-center gap-3 mb-4 relative z-10">
            <div className="w-10 h-10 rounded-xl bg-emerald-100 text-emerald-600 flex items-center justify-center">
              <Boxes size={18} />
            </div>
            <h3 className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Total Stock Units</h3>
          </div>
          <p className="text-3xl font-black text-zinc-950 relative z-10">
            {loading ? <Loader2 className="w-6 h-6 animate-spin text-zinc-300" /> : totalItems.toLocaleString()}
          </p>
        </div>

        <div className="bg-gradient-to-br from-white to-rose-50/50 border border-zinc-200 rounded-3xl p-6 flex flex-col justify-between shadow-sm relative overflow-hidden">
          <div className="absolute -right-4 -top-4 text-rose-500/5">
            <TrendingDown size={120} />
          </div>
          <div className="flex items-center gap-3 mb-4 relative z-10">
            <div className="w-10 h-10 rounded-xl bg-rose-100 text-rose-600 flex items-center justify-center">
              <AlertTriangle size={18} />
            </div>
            <h3 className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Critical Low Stock (≤ 5)</h3>
          </div>
          <p className="text-3xl font-black text-rose-600 relative z-10">
            {loading ? <Loader2 className="w-6 h-6 animate-spin text-zinc-300" /> : lowStockItems.length}
          </p>
        </div>

        <div className="bg-gradient-to-br from-white to-indigo-50/50 border border-zinc-200 rounded-3xl p-6 flex flex-col justify-between shadow-sm relative overflow-hidden">
          <div className="absolute -right-4 -top-4 text-indigo-500/5">
            <DollarSign size={120} />
          </div>
          <div className="flex items-center gap-3 mb-4 relative z-10">
            <div className="w-10 h-10 rounded-xl bg-indigo-100 text-indigo-600 flex items-center justify-center">
              <DollarSign size={18} />
            </div>
            <h3 className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Total Inventory Value</h3>
          </div>
          <p className="text-3xl font-black text-zinc-950 relative z-10">
            {loading ? <Loader2 className="w-6 h-6 animate-spin text-zinc-300" /> : `$${totalValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
          </p>
        </div>
      </div>

      {/* LOW STOCK ALARM ALERT */}
      {!loading && lowStockItems.length > 0 && (
        <div className="bg-rose-500 text-white rounded-2xl p-4 shadow-lg shadow-rose-500/20 flex flex-col md:flex-row md:items-center justify-between gap-4 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full blur-3xl -mr-16 -mt-16 pointer-events-none" />
          <div className="flex items-center gap-3 relative z-10">
            <div className="p-2 bg-white/20 rounded-xl animate-pulse">
              <AlertTriangle className="w-5 h-5" />
            </div>
            <div>
              <h4 className="font-extrabold text-sm uppercase tracking-wider">Critical Inventory Alert</h4>
              <p className="text-white/80 text-[10px] mt-0.5 font-bold uppercase tracking-widest">
                {lowStockItems.length} SKU variants require immediate restock
              </p>
            </div>
          </div>
        </div>
      )}

      {/* SEARCH AND GRID */}
      <div className="bg-white rounded-3xl border border-zinc-200 p-2 shadow-sm overflow-hidden">
        <div className="p-4 border-b border-zinc-100 bg-zinc-50/50 rounded-t-3xl flex flex-col sm:flex-row items-center gap-4">
          <div className="relative w-full max-w-md">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 w-4 h-4" />
            <input
              type="text"
              placeholder="Search variants by title, SKU, or color..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full border border-zinc-200 rounded-xl pl-11 pr-4 py-3 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:border-transparent transition bg-white text-sm shadow-sm"
            />
          </div>

          <select
            value={stockFilter}
            onChange={(e) => setStockFilter(e.target.value)}
            className="w-full sm:w-auto border border-zinc-200 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-zinc-950 transition bg-white text-sm shadow-sm text-zinc-600 font-medium cursor-pointer"
          >
            <option value="all">All Stock Levels</option>
            <option value="in">In Stock (&gt;5)</option>
            <option value="low">Low Stock (1-5)</option>
            <option value="out">Out of Stock (0)</option>
          </select>
        </div>

        {/* INVENTORY TABLE */}
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-left min-w-[1000px]">
            <thead>
              <tr className="border-b border-zinc-100 text-zinc-400 text-[9px] font-black uppercase tracking-widest bg-white">
                <th className="py-4 px-6">Product & Image</th>
                <th className="py-4 px-6">SKU Code</th>
                <th className="py-4 px-6">Attributes</th>
                <th className="py-4 px-6">Value / Unit</th>
                <th className="py-4 px-6">Live Stock</th>
                <th className="py-4 px-6 text-center">Modify</th>
              </tr>
            </thead>
            
            <tbody className="divide-y divide-zinc-100">
              {loading ? (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <Loader2 className="w-8 h-8 animate-spin text-zinc-300 mx-auto mb-3" />
                    <p className="text-xs text-zinc-400 font-bold uppercase tracking-widest">Syncing Matrix...</p>
                  </td>
                </tr>
              ) : paginatedInventory.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <Boxes className="w-8 h-8 text-zinc-200 mx-auto mb-3" />
                    <p className="text-xs text-zinc-400 font-bold uppercase tracking-widest">No variants found</p>
                  </td>
                </tr>
              ) : (
                paginatedInventory.map((item) => {
                  const isLow = item.stock <= 5
                  const isEditing = editingId === item.id

                  return (
                    <tr
                      key={item.id}
                      className={`transition duration-200 group ${isLow ? "bg-rose-50/40 hover:bg-rose-50/80" : "hover:bg-zinc-50/80"}`}
                    >
                      {/* TITLE & IMAGE */}
                      <td className="py-4 px-6">
                        <div className="flex items-center gap-4">
                          <div className="w-10 h-12 rounded-lg bg-zinc-100 border border-zinc-200/60 overflow-hidden shrink-0 shadow-sm">
                            {item.productImage ? (
                              <img src={item.productImage} alt={item.productName} className="w-full h-full object-cover group-hover:scale-110 transition duration-500" />
                            ) : (
                              <div className="w-full h-full flex items-center justify-center text-zinc-300 bg-white"><Boxes size={16} /></div>
                            )}
                          </div>
                          <div>
                            <h5 className="font-bold text-zinc-900 text-sm group-hover:text-indigo-600 transition line-clamp-1 max-w-[200px]">
                              {item.productName}
                            </h5>
                            <span className="text-[9px] text-zinc-400 font-bold uppercase tracking-widest">
                              {item.productCategory}
                            </span>
                          </div>
                        </div>
                      </td>

                      {/* SKU */}
                      <td className="py-4 px-6">
                        <span className="font-mono text-xs text-zinc-600 font-bold bg-zinc-100 px-2 py-1 rounded-md border border-zinc-200">
                          {item.sku}
                        </span>
                      </td>

                      {/* ATTRIBUTES */}
                      <td className="py-4 px-6">
                        <div className="flex flex-col gap-1.5">
                          <div className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-wider text-zinc-600">
                            <span className="w-3 h-3 rounded-full border border-black/10 shadow-sm" style={{ backgroundColor: item.color === 'Black' || item.color === 'Obsidian Black' ? '#18181b' : item.color === 'White' || item.color === 'Ivory' ? '#f4f4f5' : item.color }} />
                            {item.color}
                          </div>
                          <div className="flex items-center gap-2">
                            <span className="px-2 py-0.5 bg-zinc-900 text-white rounded text-[9px] font-black tracking-widest">{item.size}</span>
                            {item.length && (
                              <span className="px-2 py-0.5 bg-zinc-200 text-zinc-700 rounded text-[9px] font-black tracking-widest border border-zinc-300">{item.length}</span>
                            )}
                          </div>
                        </div>
                      </td>

                      {/* PRICE */}
                      <td className="py-4 px-6 font-mono text-sm font-black text-zinc-900">
                        ${item.price.toFixed(2)}
                      </td>

                      {/* STOCK LEVEL */}
                      <td className="py-4 px-6">
                        {isEditing ? (
                          <div className="flex items-center gap-1 bg-white p-1 rounded-xl border border-indigo-200 shadow-inner w-fit">
                            <button
                              onClick={() => setTempStock((p) => Math.max(0, p - 1))}
                              className="w-7 h-7 flex items-center justify-center rounded-lg bg-zinc-50 hover:bg-zinc-200 cursor-pointer text-zinc-600 transition"
                            >
                              <Minus size={12} />
                            </button>
                            <input
                              type="number"
                              value={tempStock}
                              onChange={(e) => setTempStock(Math.max(0, Number(e.target.value)))}
                              className="w-12 text-center font-bold text-sm bg-transparent focus:outline-none"
                            />
                            <button
                              onClick={() => setTempStock((p) => p + 1)}
                              className="w-7 h-7 flex items-center justify-center rounded-lg bg-zinc-50 hover:bg-zinc-200 cursor-pointer text-zinc-600 transition"
                            >
                              <Plus size={12} />
                            </button>
                          </div>
                        ) : (
                          <span
                            className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs font-black border ${
                              isLow
                                ? "bg-rose-100 text-rose-700 border-rose-200"
                                : "bg-emerald-50 text-emerald-700 border-emerald-200"
                            }`}
                          >
                            {item.stock} Units
                          </span>
                        )}
                      </td>

                      {/* ACTION CONTROL */}
                      <td className="py-4 px-6 text-center">
                        {isEditing ? (
                          <button
                            onClick={() => saveStockChange(item.id)}
                            disabled={saving}
                            className="w-9 h-9 mx-auto rounded-xl bg-indigo-600 text-white hover:bg-indigo-500 hover:shadow-lg hover:shadow-indigo-600/20 transition-all flex items-center justify-center cursor-pointer disabled:opacity-50"
                            title="Save Inventory Count"
                          >
                            {saving ? <Loader2 size={14} className="animate-spin" /> : <Check size={16} strokeWidth={3} />}
                          </button>
                        ) : (
                          <button
                            onClick={() => startEditing(item)}
                            className="w-9 h-9 mx-auto rounded-xl border border-transparent hover:border-zinc-300 hover:bg-white text-zinc-400 hover:text-indigo-600 hover:shadow-sm transition-all flex items-center justify-center cursor-pointer"
                            title="Adjust Stock Level"
                          >
                            <Edit2 size={14} />
                          </button>
                        )}
                      </td>
                    </tr>
                  )
                })
              )}
            </tbody>
          </table>
        </div>

        {/* PAGINATION CONTROLS */}
        {!loading && totalPages > 1 && (
          <div className="flex flex-col sm:flex-row items-center justify-between border-t border-zinc-100 p-4 gap-4 bg-zinc-50/30 rounded-b-3xl">
            <p className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">
              Showing {(currentPage - 1) * itemsPerPage + 1} to {Math.min(currentPage * itemsPerPage, filteredInventory.length)} of {filteredInventory.length} variants
            </p>
            <div className="flex gap-1.5 overflow-x-auto pb-1 sm:pb-0">
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="px-3 py-1.5 rounded-lg border border-zinc-200 text-xs font-bold text-zinc-600 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-white hover:shadow-sm transition bg-zinc-50"
              >
                Prev
              </button>
              <div className="flex gap-1">
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => {
                  // Basic pagination logic to avoid rendering too many buttons
                  if (
                    page === 1 || 
                    page === totalPages || 
                    (page >= currentPage - 1 && page <= currentPage + 1)
                  ) {
                    return (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`w-8 h-8 rounded-lg text-xs font-bold transition flex items-center justify-center ${
                          currentPage === page 
                            ? 'bg-zinc-950 text-white shadow-md' 
                            : 'border border-zinc-200 text-zinc-600 hover:bg-white hover:shadow-sm bg-zinc-50'
                        }`}
                      >
                        {page}
                      </button>
                    )
                  } else if (page === currentPage - 2 || page === currentPage + 2) {
                    return <span key={page} className="w-8 h-8 flex items-center justify-center text-zinc-400 text-xs">...</span>
                  }
                  return null;
                })}
              </div>
              <button
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="px-3 py-1.5 rounded-lg border border-zinc-200 text-xs font-bold text-zinc-600 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-white hover:shadow-sm transition bg-zinc-50"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}