"use client"

import { useEffect, useState } from "react"
import {
  Package,
  Search,
  Eye,
  Trash2,
  Loader2,
  X,
  CreditCard,
  Calendar,
  TrendingUp,
  RotateCcw,
  DollarSign,
  Filter,
  Truck,
  CheckCircle2,
  AlertCircle,
  Printer,
  Clock
} from "lucide-react"
import api from "@/lib/axios"
import { useCurrency } from "@/providers/CurrencyProvider"
import Swal from "sweetalert2";

type Product = {
  id: string
  title: string
  thumbnail: string
}

type Variant = {
  id: string
  size: string
  color: string
  length: string | null
  product: Product
}

type OrderItem = {
  id: string
  quantity: number
  price: number
  variant: Variant
}

type Payment = {
  id: string
  provider: string
  amount: number
  status: string
  transactionId: string | null
  createdAt: string
}

type User = {
  id: string
  name: string
  email: string
  phone: string | null
}

type Order = {
  id: string
  userId: string
  user: User
  totalAmount: number
  status: "PENDING" | "PROCESSING" | "SHIPPED" | "DELIVERED" | "CANCELLED"
  paymentStatus: "PENDING" | "PAID" | "FAILED" | "REFUNDED"
  shippingAddress: string
  shippingPhone: string
  items: OrderItem[]
  payment?: Payment | null
  createdAt: string
  updatedAt: string
}

export default function AdminOrdersPage() {
  const { formatPrice } = useCurrency()
  const [orders, setOrders] = useState<Order[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null)
  
  // Search & Filter state
  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState<string>("ALL")
  const [paymentFilter, setPaymentFilter] = useState<string>("ALL")
  
  // Mutating loading state
  const [updatingId, setUpdatingId] = useState<string | null>(null)
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalRecords, setTotalRecords] = useState(0)

  async function fetchOrders() {
    try {
      setLoading(true)
      const res = await api.get(`/admin/orders?page=${page}&limit=20&search=${searchQuery}&status=${statusFilter}&paymentStatus=${paymentFilter}`)
      const fetchedOrders = Array.isArray(res.data.data) ? res.data.data : Array.isArray(res.data) ? res.data : []
      setOrders(fetchedOrders)
      if (res.data.meta) {
        setTotalPages(res.data.meta.totalPages)
        setTotalRecords(res.data.meta.total)
      }
    } catch (error) {
      console.error("Failed to fetch orders:", error)
    } finally {
      setLoading(false)
    }
  }

  // Debounced fetch
  useEffect(() => {
    const handler = setTimeout(() => {
      fetchOrders()
    }, 500)
    return () => clearTimeout(handler)
  }, [page, searchQuery, statusFilter, paymentFilter])

  // Reset page
  useEffect(() => {
    setPage(1)
  }, [searchQuery, statusFilter, paymentFilter])

  // Sync selected order detailed view when list changes
  useEffect(() => {
    if (selectedOrder) {
      const updated = orders.find(o => o.id === selectedOrder.id)
      if (updated) {
        setSelectedOrder(updated)
      }
    }
  }, [orders])

  async function handleUpdateStatus(orderId: string, payload: { status?: string; paymentStatus?: string }) {
    try {
      setUpdatingId(orderId)
      await api.patch(`/admin/orders/${orderId}`, payload)
      // Refresh list
      const res = await api.get("/admin/orders")
      const updatedOrders = Array.isArray(res.data.data) ? res.data.data : Array.isArray(res.data) ? res.data : []
      setOrders(updatedOrders)
    } catch (error) {
      Swal.fire({ text: "Failed to update status details.", confirmButtonColor: "#18181b", icon: "error" })
      console.error(error)
    } finally {
      setUpdatingId(null)
    }
  }

  async function handleDeleteOrder(orderId: string) {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to permanently delete this order? This will remove all items and payment records.", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return
    try {
      setDeletingId(orderId)
      await api.delete(`/admin/orders/${orderId}`)
      setSelectedOrder(null)
      fetchOrders()
    } catch (error) {
      Swal.fire({ text: "Failed to delete order due to database constraints.", confirmButtonColor: "#18181b", icon: "error" })
      console.error(error)
    } finally {
      setDeletingId(null)
    }
  }

  // Filter logic handled by server

  // Calculations for stats
  const totalOrders = orders.length
  const totalRevenue = orders
    .filter(o => o.paymentStatus === "PAID" || o.status === "DELIVERED")
    .reduce((sum, o) => sum + o.totalAmount, 0)
  const pendingOrders = orders.filter(o => o.status === "PENDING" || o.status === "PROCESSING").length
  const completedOrders = orders.filter(o => o.status === "DELIVERED").length

  // Status badging styles
  const getStatusBadge = (status: Order["status"]) => {
    const styles = {
      PENDING: "bg-amber-50 text-amber-700 border-amber-200/60",
      PROCESSING: "bg-indigo-50 text-indigo-700 border-indigo-200/60",
      SHIPPED: "bg-sky-50 text-sky-700 border-sky-200/60",
      DELIVERED: "bg-emerald-50 text-emerald-700 border-emerald-200/60",
      CANCELLED: "bg-rose-50 text-rose-700 border-rose-200/60"
    }
    return styles[status] || "bg-zinc-50 text-zinc-650"
  }

  const getPaymentStatusBadge = (status: Order["paymentStatus"]) => {
    const styles = {
      PENDING: "bg-zinc-100 text-zinc-600 border-zinc-200",
      PAID: "bg-emerald-50 text-emerald-700 border-emerald-200/60",
      FAILED: "bg-rose-50 text-rose-750 border-rose-200/60",
      REFUNDED: "bg-purple-50 text-purple-700 border-purple-200/60"
    }
    return styles[status] || "bg-zinc-50 text-zinc-650"
  }

  return (
    <>
      {/* SIDE SHEET DETAIL PANEL */}
      {selectedOrder && (
        <div className="fixed inset-0 z-50 flex justify-end bg-black/40 backdrop-blur-xs transition duration-300">
          <div className="bg-white w-full max-w-lg h-full shadow-2xl flex flex-col relative animate-in slide-in-from-right duration-350">
            {/* Modal Header */}
            <div className="p-5 border-b border-zinc-100 flex items-center justify-between bg-zinc-950 text-white">
              <div className="flex items-center gap-2">
                <div className="p-1.5 bg-white/10 rounded-lg">
                  <Package size={15} />
                </div>
                <div>
                  <h3 className="text-xs font-black tracking-widest uppercase">Order Details</h3>
                  <p className="text-[10px] font-mono text-zinc-400 mt-0.5">#{selectedOrder.id}</p>
                </div>
              </div>
              <button
                onClick={() => setSelectedOrder(null)}
                className="p-1.5 rounded-lg hover:bg-white/10 transition text-zinc-400 hover:text-white cursor-pointer"
              >
                <X size={18} />
              </button>
            </div>

            {/* Modal Content Scrollable */}
            <div className="flex-1 overflow-y-auto p-5 space-y-6">
              {/* STAGE & STATUS CONTROLS */}
              <div className="bg-zinc-50 rounded-xl p-4.5 border border-zinc-150 space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-400">Manage Statuses</span>
                  {updatingId === selectedOrder.id && <Loader2 className="w-4 h-4 animate-spin text-zinc-800" />}
                </div>

                <div className="grid grid-cols-2 gap-3.5">
                  <div>
                    <label className="block text-[8px] font-extrabold uppercase tracking-widest text-zinc-500 mb-1">Order Pipeline</label>
                    <select
                      value={selectedOrder.status}
                      onChange={(e) => handleUpdateStatus(selectedOrder.id, { status: e.target.value })}
                      disabled={updatingId !== null}
                      className="w-full text-[11px] font-bold bg-white border border-zinc-200 rounded-lg px-2.5 py-2 focus:outline-none focus:ring-1 focus:ring-zinc-800"
                    >
                      <option value="PENDING">PENDING</option>
                      <option value="PROCESSING">PROCESSING</option>
                      <option value="SHIPPED">SHIPPED</option>
                      <option value="DELIVERED">DELIVERED</option>
                      <option value="CANCELLED">CANCELLED</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-[8px] font-extrabold uppercase tracking-widest text-zinc-500 mb-1">Payment Status</label>
                    <select
                      value={selectedOrder.paymentStatus}
                      onChange={(e) => handleUpdateStatus(selectedOrder.id, { paymentStatus: e.target.value })}
                      disabled={updatingId !== null}
                      className="w-full text-[11px] font-bold bg-white border border-zinc-200 rounded-lg px-2.5 py-2 focus:outline-none focus:ring-1 focus:ring-zinc-800"
                    >
                      <option value="PENDING">PENDING</option>
                      <option value="PAID">PAID</option>
                      <option value="FAILED">FAILED</option>
                      <option value="REFUNDED">REFUNDED</option>
                    </select>
                  </div>
                </div>
              </div>

              {/* CUSTOMER & SHIPPING SUMMARY */}
              <div className="space-y-3.5">
                <h4 className="text-[10px] font-black uppercase tracking-widest text-zinc-950 border-b pb-1.5 flex items-center gap-1.5">
                  <CreditCard className="w-3.5 h-3.5 text-zinc-400" /> Customer Information
                </h4>
                
                <div className="grid grid-cols-2 gap-4 text-xs">
                  <div>
                    <span className="block text-[8px] font-extrabold text-zinc-450 uppercase tracking-widest">Name</span>
                    <span className="font-bold text-zinc-800">{selectedOrder.user.name}</span>
                  </div>
                  <div>
                    <span className="block text-[8px] font-extrabold text-zinc-450 uppercase tracking-widest">Email</span>
                    <span className="font-semibold text-zinc-650 truncate block">{selectedOrder.user.email}</span>
                  </div>
                  <div>
                    <span className="block text-[8px] font-extrabold text-zinc-450 uppercase tracking-widest">Phone</span>
                    <span className="font-semibold text-zinc-800">{selectedOrder.shippingPhone}</span>
                  </div>
                  <div>
                    <span className="block text-[8px] font-extrabold text-zinc-450 uppercase tracking-widest">Order Placed</span>
                    <span className="font-mono text-zinc-600">{new Date(selectedOrder.createdAt).toLocaleDateString("en-US", { dateStyle: "medium" })}</span>
                  </div>
                </div>

                <div className="bg-zinc-50 border border-zinc-100 rounded-lg p-3 mt-2">
                  <span className="block text-[8px] font-extrabold text-zinc-400 uppercase tracking-widest mb-1">Full Shipping Destination</span>
                  <p className="text-xs font-semibold text-zinc-700 leading-relaxed">{selectedOrder.shippingAddress}</p>
                </div>
              </div>

              {/* ORDERED ITEMS breakdown */}
              <div className="space-y-3.5">
                <h4 className="text-[10px] font-black uppercase tracking-widest text-zinc-950 border-b pb-1.5 flex items-center gap-1.5">
                  <Package className="w-3.5 h-3.5 text-zinc-400" /> Products Purchased ({selectedOrder.items.length})
                </h4>

                <div className="divide-y divide-zinc-100">
                  {selectedOrder.items.map((item) => (
                    <div key={item.id} className="py-3 flex gap-3.5 items-center">
                      <img
                        src={item.variant.product.thumbnail}
                        alt={item.variant.product.title}
                        className="w-11 h-14 object-cover rounded bg-zinc-50 border shrink-0"
                      />
                      <div className="min-w-0 flex-1">
                        <p className="text-xs font-bold text-zinc-900 truncate uppercase tracking-wide">
                          {item.variant.product.title}
                        </p>
                        <p className="text-[9px] text-zinc-400 mt-0.5 font-medium">
                          Color: {item.variant.color} · Size: {item.variant.size} {item.variant.length ? `· Length: ${item.variant.length}` : ""}
                        </p>
                        <p className="text-[9px] font-semibold text-zinc-500 mt-0.5">
                          Qty: {item.quantity} × ${item.price.toLocaleString()}
                        </p>
                      </div>
                      <div className="text-right shrink-0">
                        <span className="text-xs font-black text-zinc-950 font-mono">
                          {formatPrice(item.price * item.quantity)}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>

                <div className="border-t pt-3 flex justify-between items-baseline">
                  <span className="text-[10px] font-black uppercase tracking-widest text-zinc-950">Grand Total</span>
                  <span className="text-base font-black text-indigo-650 font-mono">
                    {formatPrice(selectedOrder.totalAmount)}
                  </span>
                </div>
              </div>

              {/* PAYMENT TRANSACTION METHOD FEED */}
              {selectedOrder.payment && (
                <div className="bg-indigo-50/40 rounded-xl p-4 border border-indigo-100/50 space-y-2">
                  <span className="block text-[8px] font-black uppercase tracking-widest text-indigo-500">Transaction details</span>
                  <div className="grid grid-cols-2 gap-2 text-[10px] font-semibold text-zinc-650">
                    <div>Payment Method: <span className="font-bold text-zinc-800 uppercase">{selectedOrder.payment.provider}</span></div>
                    <div>Transaction ID: <span className="font-mono text-zinc-800">{selectedOrder.payment.transactionId || "N/A"}</span></div>
                    <div>Amount Paid: <span className="font-bold text-zinc-800">{formatPrice(selectedOrder.payment.amount)}</span></div>
                    <div>Payment Date: <span className="font-mono text-zinc-800">{new Date(selectedOrder.payment.createdAt).toLocaleDateString()}</span></div>
                  </div>
                </div>
              )}
            </div>

            {/* Modal Footer */}
            <div className="p-4 border-t border-zinc-100 flex gap-3.5 bg-zinc-50 shrink-0">
              <a
                href={`/admin/orders/${selectedOrder.id}/invoice`}
                target="_blank"
                rel="noopener noreferrer"
                className="flex-1 py-2.5 rounded-xl border border-zinc-200 text-xs font-bold text-zinc-600 hover:bg-white hover:text-indigo-600 transition cursor-pointer flex justify-center items-center gap-1.5"
              >
                <Printer size={14} /> Download PDF
              </a>
              <button
                onClick={() => handleDeleteOrder(selectedOrder.id)}
                disabled={deletingId !== null}
                className="flex-1 py-2.5 rounded-xl bg-red-650 hover:bg-red-700 text-white text-xs font-bold transition flex items-center justify-center gap-1.5 disabled:opacity-50 cursor-pointer"
              >
                {deletingId === selectedOrder.id ? (
                  <Loader2 size={14} className="animate-spin" />
                ) : (
                  <Trash2 size={14} />
                )}
                Delete Order
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="space-y-6 max-w-7xl mx-auto p-2">
        {/* VIEW TITLE HEADER */}
        <div className="flex items-center gap-3">
          <div className="p-2.5 bg-zinc-900 text-white rounded-xl shadow-lg">
            <Package size={20} />
          </div>
          <div>
            <h1 className="text-2xl font-extrabold tracking-tight text-zinc-900">
              Order Registry
            </h1>
            <p className="text-zinc-400 text-xs mt-0.5">
              Manage client acquisitions, shipping pipeline, and retail checkouts.
            </p>
          </div>
        </div>

        {/* METRICS GRID SUMMARY */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="bg-white border rounded-2xl p-4.5 shadow-xs flex flex-col justify-between">
            <div className="flex justify-between items-center text-zinc-400">
              <Package size={16} />
              <span className="text-[7.5px] font-extrabold text-zinc-450 uppercase tracking-widest">Total Orders</span>
            </div>
            <div className="mt-2.5">
              <h3 className="text-xl font-black text-zinc-950 tracking-tight font-mono">{totalOrders}</h3>
              <p className="text-[8px] text-zinc-450 font-bold uppercase mt-0.5">Submissions</p>
            </div>
          </div>

          <div className="bg-white border rounded-2xl p-4.5 shadow-xs flex flex-col justify-between">
            <div className="flex justify-between items-center text-emerald-600">
              <DollarSign size={16} />
              <span className="text-[7.5px] font-extrabold text-zinc-450 uppercase tracking-widest">Paid Revenues</span>
            </div>
            <div className="mt-2.5">
              <h3 className="text-xl font-black text-zinc-950 tracking-tight font-mono">{formatPrice(totalRevenue)}</h3>
              <p className="text-[8px] text-emerald-600 font-bold uppercase mt-0.5">Total pipeline revenue</p>
            </div>
          </div>

          <div className="bg-white border rounded-2xl p-4.5 shadow-xs flex flex-col justify-between">
            <div className="flex justify-between items-center text-amber-500">
              <Clock size={16} />
              <span className="text-[7.5px] font-extrabold text-zinc-450 uppercase tracking-widest">In Processing</span>
            </div>
            <div className="mt-2.5">
              <h3 className="text-xl font-black text-zinc-950 tracking-tight font-mono">{pendingOrders}</h3>
              <p className="text-[8px] text-amber-600 font-bold uppercase mt-0.5">Awaiting dispatch</p>
            </div>
          </div>

          <div className="bg-white border rounded-2xl p-4.5 shadow-xs flex flex-col justify-between">
            <div className="flex justify-between items-center text-indigo-500">
              <CheckCircle2 size={16} />
              <span className="text-[7.5px] font-extrabold text-zinc-450 uppercase tracking-widest">Fulfilled</span>
            </div>
            <div className="mt-2.5">
              <h3 className="text-xl font-black text-zinc-950 tracking-tight font-mono">{completedOrders}</h3>
              <p className="text-[8px] text-indigo-650 font-bold uppercase mt-0.5">Delivered to client</p>
            </div>
          </div>
        </div>

        {/* SEARCH AND FILTERS BAR */}
        <div className="bg-white border border-zinc-150 p-4.5 rounded-2xl shadow-xs space-y-3.5">
          <div className="flex flex-col md:flex-row gap-3">
            {/* Search Input */}
            <div className="relative flex-1">
              <Search className="absolute left-3.5 top-3 w-4 h-4 text-zinc-400" />
              <input
                type="text"
                placeholder="Search by Order ID, Client Name, Email, or Phone..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-zinc-50 border border-zinc-200 rounded-xl pl-9.5 pr-4 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-zinc-800 transition"
              />
            </div>

            {/* Filter selectors */}
            <div className="flex gap-2 shrink-0">
              <div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1">
                <Filter className="w-3.5 h-3.5 text-zinc-450" />
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="bg-transparent text-[10px] font-bold text-zinc-650 focus:outline-none appearance-none cursor-pointer pr-1"
                >
                  <option value="ALL">ALL PIPELINE</option>
                  <option value="PENDING">PENDING</option>
                  <option value="PROCESSING">PROCESSING</option>
                  <option value="SHIPPED">SHIPPED</option>
                  <option value="DELIVERED">DELIVERED</option>
                  <option value="CANCELLED">CANCELLED</option>
                </select>
              </div>

              <div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1">
                <CreditCard className="w-3.5 h-3.5 text-zinc-450" />
                <select
                  value={paymentFilter}
                  onChange={(e) => setPaymentFilter(e.target.value)}
                  className="bg-transparent text-[10px] font-bold text-zinc-650 focus:outline-none appearance-none cursor-pointer pr-1"
                >
                  <option value="ALL">ALL PAYMENT</option>
                  <option value="PENDING">PENDING</option>
                  <option value="PAID">PAID</option>
                  <option value="FAILED">FAILED</option>
                  <option value="REFUNDED">REFUNDED</option>
                </select>
              </div>

              <button
                onClick={() => {
                  setSearchQuery("")
                  setStatusFilter("ALL")
                  setPaymentFilter("ALL")
                }}
                className="p-2 border border-zinc-200 rounded-xl hover:bg-zinc-50 transition cursor-pointer text-zinc-500 hover:text-zinc-800"
                title="Reset Filters"
              >
                <RotateCcw size={13} />
              </button>
            </div>
          </div>
        </div>

        {/* REGISTRY TABLE CONTAINER */}
        <div className="bg-white border border-zinc-150 rounded-2xl shadow-xs overflow-hidden">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-20">
              <Loader2 className="w-8 h-8 animate-spin text-zinc-400 mb-3" />
              <span className="text-zinc-400 text-xs font-semibold">Retrieving client transactions...</span>
            </div>
          ) : orders.length === 0 ? (
            <div className="text-center py-20 flex flex-col items-center justify-center">
              <div className="w-12 h-12 rounded-2xl bg-zinc-50 border flex items-center justify-center mb-3">
                <Package className="text-zinc-300 w-5 h-5" />
              </div>
              <h3 className="text-sm font-bold text-zinc-800">No matching orders</h3>
              <p className="text-zinc-400 mt-1 text-xs max-w-xs leading-relaxed">
                We couldn't find any orders that match the selected search parameters or filters.
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-zinc-50 border-b border-zinc-100 text-[8.5px] font-black uppercase tracking-widest text-zinc-450">
                    <th className="py-4.5 px-5">ID</th>
                    <th className="py-4.5 px-4">Client Detail</th>
                    <th className="py-4.5 px-4">Order Date</th>
                    <th className="py-4.5 px-4">Items</th>
                    <th className="py-4.5 px-4">Total Amount</th>
                    <th className="py-4.5 px-4">Order Status</th>
                    <th className="py-4.5 px-4">Payment</th>
                    <th className="py-4.5 px-5 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-zinc-100 text-xs">
                  {orders.map((order) => {
                    const itemCount = order.items.reduce((sum, item) => sum + item.quantity, 0)
                    return (
                      <tr
                        key={order.id}
                        className="hover:bg-zinc-50/50 group transition duration-150 cursor-pointer"
                        onClick={() => setSelectedOrder(order)}
                      >
                        {/* ID */}
                        <td className="py-4 px-5 font-mono text-[10px] font-semibold text-zinc-500 group-hover:text-indigo-650 transition">
                          #{order.id.slice(0, 10)}...
                        </td>

                        {/* Customer details */}
                        <td className="py-4 px-4">
                          <div className="font-bold text-zinc-900 group-hover:text-indigo-650 transition">{order.user.name}</div>
                          <div className="text-[10px] text-zinc-400 mt-0.5">{order.user.email}</div>
                          <div className="text-[10px] text-zinc-400 mt-0.5">{order.shippingPhone}</div>
                        </td>

                        {/* Created At */}
                        <td className="py-4 px-4 text-zinc-600 font-medium">
                          {new Date(order.createdAt).toLocaleDateString("en-US", {
                            dateStyle: "medium"
                          })}
                        </td>

                        {/* Items count */}
                        <td className="py-4 px-4 font-semibold text-zinc-650">
                          {itemCount} {itemCount === 1 ? "Item" : "Items"}
                        </td>

                        {/* Total Amount */}
                        <td className="py-4 px-4 font-black text-zinc-950 font-mono">
                          {formatPrice(order.totalAmount)}
                        </td>

                        {/* Order Status */}
                        <td className="py-4 px-4" onClick={(e) => e.stopPropagation()}>
                          <select
                            value={order.status}
                            onChange={(e) => handleUpdateStatus(order.id, { status: e.target.value })}
                            disabled={updatingId !== null}
                            className={`border text-[9px] font-extrabold px-2 py-1 rounded-full focus:outline-none uppercase tracking-wider cursor-pointer ${getStatusBadge(order.status)}`}
                          >
                            <option value="PENDING">PENDING</option>
                            <option value="PROCESSING">PROCESSING</option>
                            <option value="SHIPPED">SHIPPED</option>
                            <option value="DELIVERED">DELIVERED</option>
                            <option value="CANCELLED">CANCELLED</option>
                          </select>
                        </td>

                        {/* Payment Details */}
                        <td className="py-4 px-4" onClick={(e) => e.stopPropagation()}>
                          <div className="flex flex-col gap-1 items-start">
                            <span className={`border text-[8px] font-black px-2 py-0.5 rounded-md uppercase tracking-widest ${getPaymentStatusBadge(order.paymentStatus)}`}>
                              {order.paymentStatus}
                            </span>
                            <span className="text-[8.5px] font-extrabold text-zinc-400 uppercase tracking-widest font-sans pl-0.5">
                              {order.payment?.provider || "COD"}
                            </span>
                          </div>
                        </td>

                        {/* Actions */}
                        <td className="py-4 px-5 text-right" onClick={(e) => e.stopPropagation()}>
                          <div className="flex items-center justify-end gap-1.5">
                            <button
                              onClick={() => setSelectedOrder(order)}
                              className="p-1.5 rounded-lg text-zinc-400 hover:text-indigo-650 hover:bg-indigo-50 transition cursor-pointer"
                              title="Details"
                            >
                              <Eye size={14} />
                            </button>
                            <button
                              onClick={() => handleDeleteOrder(order.id)}
                              disabled={deletingId === order.id}
                              className="p-1.5 rounded-lg text-zinc-400 hover:text-red-650 hover:bg-red-50 transition cursor-pointer disabled:opacity-40"
                              title="Delete"
                            >
                              {deletingId === order.id ? (
                                <Loader2 size={14} className="animate-spin" />
                              ) : (
                                <Trash2 size={14} />
                              )}
                            </button>
                          </div>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* PAGINATION */}
        {totalPages > 1 && (
          <div className="flex justify-between items-center mt-6">
            <span className="text-xs text-zinc-500 font-medium">
              Showing page {page} of {totalPages} ({totalRecords} total)
            </span>
            <div className="flex gap-2">
              <button
                disabled={page === 1}
                onClick={() => setPage(p => p - 1)}
                className="px-4 py-2 border border-zinc-200 rounded-xl text-xs font-bold hover:bg-white disabled:opacity-50 transition cursor-pointer shadow-xs"
              >
                Previous
              </button>
              <button
                disabled={page === totalPages}
                onClick={() => setPage(p => p + 1)}
                className="px-4 py-2 border border-zinc-200 rounded-xl text-xs font-bold hover:bg-white disabled:opacity-50 transition cursor-pointer shadow-xs"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  )
}