"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { Edit, Trash2, Layers, Image, CheckCircle, HelpCircle, Loader2, Eye, X, AlertTriangle } from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

type Product = {
  id: string
  title: string
  thumbnail: string
  basePrice: number
  category?: {
    id: string
    name: string
  }
  brand?: {
    id: string
    name: string
  } | null
  sizeChart?: string | null
  variants?: Array<{
    id: string
    stock: number
  }>
}

export default function ProductTable({ categorySlug }: { categorySlug?: string }) {
  const [products, setProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(true)

  // DETAILS MODAL STATE
  const [selectedProduct, setSelectedProduct] = useState<any>(null)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [modalLoading, setModalLoading] = useState(false)

  // DELETE MODAL STATE
  const [deleteProductId, setDeleteProductId] = useState<string | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)

  // SEARCH & FILTER STATE
  const [searchQuery, setSearchQuery] = useState("")
  const [categoryFilter, setCategoryFilter] = useState("")
  const [brandFilter, setBrandFilter] = useState("")

  // PAGINATION STATE
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalRecords, setTotalRecords] = useState(0)
  const itemsPerPage = 20

  // RESET PAGE ON FILTER CHANGE
  useEffect(() => {
    setCurrentPage(1)
  }, [searchQuery, categoryFilter, brandFilter])

  const [categories, setCategories] = useState<{id: string, name: string}[]>([])
  const [brands, setBrands] = useState<{id: string, name: string}[]>([])

  // FETCH FILTERS
  async function fetchFilters() {
    try {
      const [catRes, brandRes] = await Promise.all([
        api.get("/admin/categories"),
        api.get("/admin/brands")
      ])
      setCategories(catRes.data)
      setBrands(brandRes.data)
    } catch (error) {
      console.log("Error fetching filters", error)
    }
  }

  // FETCH PRODUCTS
  async function fetchProducts() {
    try {
      setLoading(true)
      const res = await api.get(`/admin/products?page=${currentPage}&limit=${itemsPerPage}&search=${searchQuery}&categoryId=${categoryFilter}&brandId=${brandFilter}&categorySlug=${categorySlug || ""}`)
      setProducts(res.data.data || res.data)
      if (res.data.meta) {
        setTotalPages(res.data.meta.totalPages)
        setTotalRecords(res.data.meta.total)
      }
    } catch (error) {
      console.log("Error fetching products:", error)
    } finally {
      setLoading(false)
    }
  }

  // Debounced fetch
  useEffect(() => {
    const handler = setTimeout(() => {
      fetchProducts()
    }, 500)
    return () => clearTimeout(handler)
  }, [currentPage, searchQuery, categoryFilter, brandFilter, categorySlug])

  // FETCH PRODUCT DETAILS FOR MODAL
  async function showDetails(id: string) {
    try {
      setModalLoading(true)
      setIsModalOpen(true)
      const res = await api.get(`/admin/products/${id}`)
      setSelectedProduct(res.data)
    } catch (error) {
      console.error("Error fetching product details:", error)
      Swal.fire({ text: "Failed to load product details.", confirmButtonColor: "#18181b", icon: "error" })
      setIsModalOpen(false)
    } finally {
      setModalLoading(false)
    }
  }

  // CONFIRM AND DELETE PRODUCT
  async function confirmDeleteProduct() {
    if (!deleteProductId) return
    try {
      setIsDeleting(true)
      await api.delete(`/admin/products/${deleteProductId}`)
      await fetchProducts()
      setDeleteProductId(null)
    } catch (error) {
      console.log("Delete failed:", error)
      Swal.fire({ text: "Failed to delete product. It may have active constraints.", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setIsDeleting(false)
    }
  }

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

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <Loader2 className="w-10 h-10 animate-spin text-indigo-600 mb-4" />
        <span className="text-zinc-500 font-semibold text-sm">Loading curated catalog...</span>
      </div>
    )
  }

  if (products.length === 0) {
    return (
      <div className="text-center py-20 flex flex-col items-center">
        <Layers className="text-zinc-300 w-16 h-16 mb-4 animate-pulse" />
        <h3 className="text-xl font-bold text-zinc-900">Inventory is empty</h3>
        <p className="text-zinc-500 mt-1 max-w-sm text-sm">
          Get started by adding your first premium design product using the button above.
        </p>
      </div>
    )
  }

  // FILTERING HANDLED BY SERVER

  return (
    <div className="space-y-4">
      {/* FILTER & SEARCH BAR */}
      <div className="flex flex-wrap items-center gap-3 pb-2">
        <div className="relative w-full max-w-[240px]">
           <input
            type="text"
            placeholder="Search products..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full border border-zinc-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-950 transition bg-zinc-50"
          />
        </div>
        
        <select 
          value={categoryFilter} 
          onChange={(e) => setCategoryFilter(e.target.value)}
          className="border border-zinc-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-950 transition bg-zinc-50 text-zinc-600 cursor-pointer min-w-[140px]"
        >
          <option value="">All Categories</option>
          {categories.map(c => (
            <option key={c.id} value={c.id}>{c.name}</option>
          ))}
        </select>

        <select 
          value={brandFilter} 
          onChange={(e) => setBrandFilter(e.target.value)}
          className="border border-zinc-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-950 transition bg-zinc-50 text-zinc-600 cursor-pointer min-w-[120px]"
        >
          <option value="">All Brands</option>
          {brands.map(b => (
            <option key={b.id} value={b.id}>{b.name}</option>
          ))}
        </select>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full border-collapse">
          <thead>
            <tr className="border-b border-zinc-100 text-left text-zinc-400 text-xs font-extrabold uppercase tracking-widest">
              <th className="pb-5 font-extrabold pl-2">Product Info</th>
              <th className="pb-5 font-extrabold hidden md:table-cell">Inventory status</th>
              <th className="pb-5 font-extrabold">Base Price</th>
              <th className="pb-5 font-extrabold text-right pr-4">Actions</th>
            </tr>
          </thead>

          <tbody className="divide-y divide-zinc-100">
          {products.map((product) => {
            const variantCount = product.variants?.length || 0
            const totalStock = product.variants?.reduce((sum, v) => sum + v.stock, 0) || 0

            return (
              <tr
                key={product.id}
                className="group hover:bg-zinc-50/50 transition duration-200"
              >
                {/* INFO CELL */}
                <td className="py-5 pl-2">
                  <div className="flex items-center gap-4">
                    <div className="w-16 h-16 rounded-2xl bg-zinc-50 border border-zinc-100 overflow-hidden shrink-0 flex items-center justify-center shadow-sm group-hover:border-indigo-200 group-hover:shadow-md transition duration-300">
                      <img
                        src={product.thumbnail}
                        alt={product.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition duration-300"
                      />
                    </div>

                    <div className="space-y-1">
                      <h3 className="font-extrabold text-zinc-950 text-sm group-hover:text-indigo-600 transition truncate max-w-[200px] md:max-w-xs">
                        {product.title}
                      </h3>

                      <div className="flex flex-wrap gap-1.5 items-center">
                        {/* CATEGORY TAG */}
                        {product.category && (
                          <span className="text-[9px] font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md bg-indigo-50 text-indigo-600 border border-indigo-100/50">
                            {product.category.name}
                          </span>
                        )}

                        {/* BRAND TAG */}
                        {product.brand && (
                          <span className="text-[9px] font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md bg-amber-50 text-amber-600 border border-amber-100/50">
                            {product.brand.name}
                          </span>
                        )}

                        {/* SIZE CHART PRESENT pill */}
                        {product.sizeChart ? (
                          <span className="text-[9px] font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md bg-emerald-50 text-emerald-600 border border-emerald-100/50 flex items-center gap-0.5">
                            <CheckCircle size={8} />
                            Chart
                          </span>
                        ) : (
                          <span className="text-[9px] font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md bg-zinc-100 text-zinc-400 flex items-center gap-0.5">
                            <HelpCircle size={8} />
                            No Chart
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </td>

                {/* INVENTORY CELL */}
                <td className="py-5 hidden md:table-cell">
                  <div className="flex flex-col gap-1">
                    <div className="flex items-center gap-1 text-xs text-zinc-900 font-bold">
                      <Layers size={12} className="text-zinc-400" />
                      <span>{variantCount} Variants</span>
                    </div>
                    <span className={`text-[10px] font-extrabold uppercase ${totalStock > 0 ? "text-emerald-500" : "text-rose-500"}`}>
                      {totalStock > 0 ? `${totalStock} Units in stock` : "Out of Stock"}
                    </span>
                  </div>
                </td>

                {/* PRICE CELL */}
                <td className="py-5 font-black text-zinc-950 font-mono tracking-tight text-sm">
                  ${product.basePrice.toFixed(2)}
                </td>

                {/* ACTIONS CELL */}
                <td className="py-5 text-right pr-4">
                  <div className="inline-flex gap-2 items-center">
                    {/* VIEW DETAILS ACTION */}
                    <button
                      onClick={() => showDetails(product.id)}
                      className="p-2.5 rounded-xl border border-zinc-200 hover:bg-zinc-50 text-zinc-500 hover:text-zinc-950 transition cursor-pointer flex items-center justify-center shadow-sm"
                    >
                      <Eye size={14} />
                    </button>

                    {/* EDIT ACTION */}
                    <Link
                      href={`/admin/products/${product.id}/edit`}
                      className="p-2.5 rounded-xl bg-gradient-to-r from-violet-600 to-indigo-600 hover:opacity-90 text-white transition shadow-md shadow-indigo-600/10 flex items-center justify-center"
                    >
                      <Edit size={14} className="stroke-[2.5]" />
                    </Link>

                    {/* DELETE ACTION */}
                    <button
                      onClick={() => setDeleteProductId(product.id)}
                      className="p-2.5 rounded-xl border border-zinc-200/60 hover:border-rose-100 hover:bg-rose-50/50 text-zinc-400 hover:text-rose-500 transition cursor-pointer flex items-center justify-center"
                    >
                      <Trash2 size={14} />
                    </button>
                  </div>
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>

      {/* PAGINATION CONTROLS */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between border-t border-zinc-100 pt-4 px-2">
          <p className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">
            Showing Page {currentPage} of {totalPages} ({totalRecords} total products)
          </p>
          <div className="flex gap-1.5">
            <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-zinc-50 transition"
            >
              Prev
            </button>
            <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-zinc-50 transition"
            >
              Next
            </button>
          </div>
        </div>
      )}

      {/* DETAILED OVERLAY SPEC MODAL */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 bg-zinc-950/40 backdrop-blur-sm flex items-center justify-center p-4 transition-all duration-300">
          <div className="bg-white border border-zinc-150 rounded-3xl max-w-2xl w-full max-h-[85vh] overflow-y-auto shadow-2xl p-6 relative space-y-6">
            
            {/* CLOSE TRIGGER */}
            <button
              onClick={() => {
                setIsModalOpen(false)
                setSelectedProduct(null)
              }}
              className="absolute top-4 right-4 p-2 rounded-full border border-zinc-200 bg-zinc-50 hover:bg-zinc-100 text-zinc-500 hover:text-zinc-900 transition flex items-center justify-center cursor-pointer shadow-sm"
            >
              <X size={14} />
            </button>

            {modalLoading ? (
              <div className="flex flex-col items-center justify-center py-20">
                <Loader2 className="w-10 h-10 animate-spin text-zinc-950 mb-3" />
                <span className="text-zinc-500 font-bold uppercase tracking-widest text-[10px]">Loading Spec Sheets...</span>
              </div>
            ) : selectedProduct ? (
              <div className="space-y-6">
                
                {/* HEADER SECTION */}
                <div className="space-y-2 border-b border-zinc-100 pb-4">
                  <div className="flex flex-wrap gap-1.5 items-center">
                    {selectedProduct.category && (
                      <span className="text-[9px] font-black uppercase tracking-widest px-2 py-0.5 rounded bg-zinc-950 text-white">
                        {selectedProduct.category.name}
                      </span>
                    )}
                    {selectedProduct.brand && (
                      <span className="text-[9px] font-black uppercase tracking-widest px-2 py-0.5 rounded border border-zinc-200 text-zinc-650 bg-zinc-50">
                        {selectedProduct.brand.name}
                      </span>
                    )}
                  </div>
                  <h2 className="text-base font-black text-zinc-950">{selectedProduct.title}</h2>
                  <p className="text-[10px] font-mono text-zinc-400 font-semibold uppercase tracking-wider">{selectedProduct.slug}</p>
                </div>

                {/* DETAILS CONTENT */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {/* LEFT: GALLERY & IMAGES */}
                  <div className="space-y-4">
                    <div className="aspect-square rounded-2xl overflow-hidden border border-zinc-150 bg-zinc-50 shadow-inner">
                      <img
                        src={selectedProduct.thumbnail}
                        alt={selectedProduct.title}
                        className="w-full h-full object-cover animate-fadeIn"
                      />
                    </div>

                    {/* PHOTO GALLERY */}
                    {selectedProduct.images && selectedProduct.images.length > 0 && (
                      <div>
                        <h4 className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest mb-2">Gallery Assets</h4>
                        <div className="grid grid-cols-4 gap-2">
                          {selectedProduct.images.map((img: any, idx: number) => (
                            <div key={idx} className="aspect-square rounded-xl overflow-hidden border border-zinc-150 bg-zinc-50 relative">
                              <img src={img.url} alt="Gallery" className="w-full h-full object-cover" />
                              {img.color && (
                                <span className="absolute bottom-0.5 left-0.5 right-0.5 text-[7px] font-black uppercase bg-zinc-950/80 text-white py-0.5 px-1 rounded text-center truncate backdrop-blur-sm">
                                  {img.color}
                                </span>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* RIGHT: SPECS, STOCK VARIANTS & SIZE CHART */}
                  <div className="space-y-5">
                    {/* BASE PRICE */}
                    <div className="bg-zinc-50/50 border border-zinc-150 p-3.5 rounded-2xl flex items-center justify-between">
                      <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">Base Value</span>
                      <span className="font-mono text-sm font-black text-zinc-950">${selectedProduct.basePrice.toFixed(2)}</span>
                    </div>

                    {/* DESCRIPTION */}
                    <div className="space-y-1.5">
                      <h4 className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest">Narrative Story</h4>
                      <p className="text-xs text-zinc-600 leading-relaxed font-medium bg-zinc-50/30 p-3 rounded-2xl border border-zinc-150/40">
                        {selectedProduct.description || "No description provided."}
                      </p>
                    </div>

                    {/* STOCK VARIANTS */}
                    <div className="space-y-2">
                      <h4 className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest">Stock Options ({selectedProduct.variants?.length || 0})</h4>
                      {selectedProduct.variants && selectedProduct.variants.length > 0 ? (
                        <div className="max-h-36 overflow-y-auto border border-zinc-150 rounded-2xl divide-y divide-zinc-100 bg-white">
                          {selectedProduct.variants.map((v: any, idx: number) => (
                            <div key={idx} className="p-2 flex items-center justify-between text-[11px] font-semibold">
                              <div className="flex items-center gap-1.5">
                                <span className="px-1.5 py-0.5 bg-zinc-950 text-white rounded text-[8px] font-black uppercase">{v.size}</span>
                                <span className="text-zinc-650 font-bold">{v.color}</span>
                                {v.length && (
                                  <span className="px-1 py-0.5 bg-zinc-50 border border-zinc-150 text-zinc-500 rounded text-[9px] font-bold">{v.length}</span>
                                )}
                              </div>
                              <div className="flex items-center gap-3">
                                <span className="font-mono text-zinc-400 text-[9px] font-bold">{v.sku}</span>
                                <span className={`font-bold ${v.stock > 0 ? "text-emerald-600" : "text-rose-500"}`}>
                                  {v.stock} units
                                </span>
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <p className="text-[10px] text-zinc-400 italic">No variants added to this product.</p>
                      )}
                    </div>

                    {/* SIZE CHART PREVIEW */}
                    {selectedProduct.sizeChart && (
                      <div className="space-y-2">
                        <h4 className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest">Size Chart Guide</h4>
                        <div className="aspect-[4/3] w-full rounded-2xl overflow-hidden border border-zinc-150 bg-zinc-50 shadow-sm relative group">
                          <img src={selectedProduct.sizeChart} alt="Size Chart Guide" className="w-full h-full object-contain" />
                        </div>
                      </div>
                    )}

                  </div>
                </div>

              </div>
            ) : null}

          </div>
        </div>
      )}

      {/* DELETE CONFIRMATION MODAL */}
      {deleteProductId && (
        <div className="fixed inset-0 z-[60] bg-zinc-950/40 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white rounded-3xl max-w-md w-full shadow-2xl overflow-hidden border border-zinc-150 animate-in zoom-in-95 duration-200">
            {/* Warning Header Banner */}
            <div className="bg-rose-50 border-b border-rose-100 p-6 flex flex-col items-center text-center">
              <div className="w-16 h-16 bg-rose-100 text-rose-600 rounded-full flex items-center justify-center mb-4 shadow-sm border border-rose-200">
                <AlertTriangle size={28} className="stroke-[2.5]" />
              </div>
              <h3 className="text-lg font-black text-rose-900 tracking-tight">Destructive Action</h3>
              <p className="text-xs text-rose-700 font-medium mt-1">This operation cannot be undone.</p>
            </div>
            
            {/* Warning Content */}
            <div className="p-6 space-y-4">
              <p className="text-sm text-zinc-600 leading-relaxed font-medium">
                Are you absolutely sure you want to permanently delete this product? The following associated data will also be <strong className="text-zinc-950 font-black">permanently destroyed</strong>:
              </p>
              
              <ul className="text-xs text-zinc-500 space-y-2 bg-zinc-50 p-4 rounded-xl border border-zinc-100">
                <li className="flex items-start gap-2">
                  <span className="text-rose-500 font-bold mt-0.5">•</span>
                  <span>All product <strong>Variants</strong> (Sizes, Colors, SKUs)</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-rose-500 font-bold mt-0.5">•</span>
                  <span>All uploaded <strong>Gallery Images</strong></span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-rose-500 font-bold mt-0.5">•</span>
                  <span>Active items inside <strong>User Carts & Wishlists</strong></span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-rose-500 font-bold mt-0.5">•</span>
                  <span>Customer <strong>Reviews</strong> and <strong>Inventory Logs</strong></span>
                </li>
              </ul>
            </div>

            {/* Action Buttons */}
            <div className="p-4 border-t border-zinc-100 bg-zinc-50 flex items-center gap-3 justify-end">
              <button
                onClick={() => setDeleteProductId(null)}
                disabled={isDeleting}
                className="px-5 py-2.5 rounded-xl text-sm font-bold text-zinc-600 hover:text-zinc-950 hover:bg-zinc-200/50 transition cursor-pointer disabled:opacity-50"
              >
                Cancel
              </button>
              <button
                onClick={confirmDeleteProduct}
                disabled={isDeleting}
                className="px-6 py-2.5 rounded-xl text-sm font-black text-white bg-rose-600 hover:bg-rose-500 shadow-md shadow-rose-600/20 transition cursor-pointer flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isDeleting ? (
                  <>
                    <Loader2 size={16} className="animate-spin" />
                    Deleting...
                  </>
                ) : (
                  "Yes, Delete Product"
                )}
              </button>
            </div>
          </div>
        </div>
      )}
      </div>
    </div>
  )
}