"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/auth";
import { Search, Loader2, ChevronLeft, ChevronRight, MessageCircle } from "lucide-react";

const API = process.env.NEXT_PUBLIC_API_URL ;

export default function AdminOrdersPage() {
  const { token } = useAuth();
  const [orders, setOrders] = useState<any[]>([]);
  const [pagination, setPagination] = useState({ total: 0, page: 1, totalPages: 1 });
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [paymentFilter, setPaymentFilter] = useState("");
  const [checkingId, setCheckingId] = useState<number | null>(null);

  const fetchOrders = async (page = 1) => {
    if (!token) return;
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), limit: "20" });
      if (statusFilter) params.set("status", statusFilter);
      if (paymentFilter) params.set("payment", paymentFilter);
      if (search) params.set("search", search);
      const res = await fetch(`${API}/api/admin/orders?${params}`, { headers: { Authorization: `Bearer ${token}` } });
      const json = await res.json();
      if (json.success) { setOrders(json.data); setPagination(json.pagination); }
    } catch (err) { console.error(err); } finally { setLoading(false); }
  };

  const checkVipStatus = async (id: number) => {
    setCheckingId(id);
    try {
      const res = await fetch(`${API}/api/admin/orders/${id}/check-vip`, { method: "POST", headers: { Authorization: `Bearer ${token}` } });
      const json = await res.json();
      alert(json.success ? `Status: ${JSON.stringify(json.data?.data?.[0]?.status || "unknown")}` : json.message);
      fetchOrders(pagination.page);
    } catch { alert("Gagal cek status"); } finally { setCheckingId(null); }
  };

  useEffect(() => { fetchOrders(); }, [token, statusFilter, paymentFilter]);

  const statusBadge = (s: string) => {
    const m: Record<string, { bg: string; text: string; label: string }> = {
      success: { bg: "bg-green-500/10", text: "text-green-400", label: "Completed" },
      processing: { bg: "bg-blue-500/10", text: "text-blue-400", label: "Processing" },
      pending: { bg: "bg-yellow-500/10", text: "text-yellow-400", label: "Pending" },
      failed: { bg: "bg-red-500/10", text: "text-red-400", label: "Failed" },
    };
    return m[s] || { bg: "bg-white/5", text: "text-muted", label: s };
  };

  const Pagination = () => {
    if (pagination.totalPages <= 1) return null;
    return (
      <div className="flex items-center justify-between px-4 py-3 border-t border-dark-border">
        <p className="text-[10px] sm:text-xs text-muted">Total: {pagination.total}</p>
        <div className="flex items-center gap-1">
          <button onClick={() => fetchOrders(pagination.page - 1)} disabled={pagination.page <= 1} className="w-7 h-7 rounded-lg bg-white/5 text-muted hover:text-white disabled:opacity-30 flex items-center justify-center">
            <ChevronLeft size={12} />
          </button>
          {Array.from({ length: Math.min(pagination.totalPages, 5) }, (_, i) => i + 1).map((p) => (
            <button key={p} onClick={() => fetchOrders(p)}
              className={`w-7 h-7 rounded-lg text-[10px] font-bold flex items-center justify-center ${pagination.page === p ? "bg-red-500 text-white" : "bg-white/5 text-muted hover:text-white"}`}>
              {p}
            </button>
          ))}
          {pagination.totalPages > 5 && <span className="text-[10px] text-muted px-1">...{pagination.totalPages}</span>}
          <button onClick={() => fetchOrders(pagination.page + 1)} disabled={pagination.page >= pagination.totalPages} className="w-7 h-7 rounded-lg bg-white/5 text-muted hover:text-white disabled:opacity-30 flex items-center justify-center">
            <ChevronRight size={12} />
          </button>
        </div>
      </div>
    );
  };

  return (
    <div className="space-y-4">
      {/* Header + Filters */}
      <div className="space-y-3">
        <h1 className="text-lg sm:text-xl font-bold text-white">Pesanan</h1>
        <div className="flex flex-wrap items-center gap-2">
          <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="bg-dark-surface border border-dark-border rounded-lg px-2.5 py-2 text-[11px] text-white focus:outline-none cursor-pointer">
            <option value="">Semua Status</option>
            <option value="pending">Pending</option>
            <option value="processing">Processing</option>
            <option value="success">Completed</option>
            <option value="failed">Failed</option>
          </select>
          <select value={paymentFilter} onChange={(e) => setPaymentFilter(e.target.value)} className="bg-dark-surface border border-dark-border rounded-lg px-2.5 py-2 text-[11px] text-white focus:outline-none cursor-pointer">
            <option value="">Semua Bayar</option>
            <option value="PAID">Paid</option>
            <option value="UNPAID">Unpaid</option>
            <option value="EXPIRED">Expired</option>
          </select>
          <div className="relative flex-1 min-w-[140px]">
            <Search size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted" />
            <input value={search} onChange={(e) => setSearch(e.target.value)} onKeyDown={(e) => e.key === "Enter" && fetchOrders()}
              placeholder="Cari..." className="w-full bg-dark-surface border border-dark-border rounded-lg pl-7 pr-3 py-2 text-[11px] text-white placeholder:text-muted focus:outline-none focus:border-red-500/50" />
          </div>
        </div>
      </div>

      {/* Desktop Table */}
      <div className="hidden md:block bg-dark-surface rounded-xl border border-dark-border overflow-hidden">
        <div className="grid grid-cols-12 gap-3 px-4 py-3 border-b border-dark-border text-[10px] text-muted font-medium uppercase tracking-wider">
          <div className="col-span-2">Invoice</div>
          <div className="col-span-1">Tanggal</div>
          <div className="col-span-3">Produk</div>
          <div className="col-span-2">ID Game</div>
          <div className="col-span-1 text-right">Harga</div>
          <div className="col-span-1 text-center">Status</div>
          <div className="col-span-2 text-center">Opsi</div>
        </div>
        {loading ? (
          <div className="text-center py-16 text-muted"><Loader2 className="inline animate-spin mr-2" size={16} />Memuat...</div>
        ) : orders.length === 0 ? (
          <div className="text-center py-16 text-muted text-xs">Tidak ada pesanan</div>
        ) : (
          <div className="divide-y divide-dark-border">
            {orders.map((o) => {
              const sb = statusBadge(o.fulfill_status);
              return (
                <div key={o.id} className="grid grid-cols-12 gap-3 px-4 py-3 hover:bg-white/[0.015] transition-colors items-center">
                  <div className="col-span-2">
                    <p className="text-xs font-bold text-white">{o.invoice_no}</p>
                    <p className={`text-[9px] font-bold mt-0.5 ${o.payment_status === "PAID" ? "text-green-400" : o.payment_status === "EXPIRED" ? "text-red-400" : "text-yellow-400"}`}>{o.payment_status}</p>
                  </div>
                  <div className="col-span-1"><p className="text-[10px] text-muted">{new Date(o.createdAt || o.created_at).toLocaleDateString("id-ID", { day: "2-digit", month: "short" })}</p></div>
                  <div className="col-span-3">
                    <p className="text-xs font-medium text-white truncate">{o.game_name}</p>
                    <p className="text-[10px] text-muted truncate">{o.product?.product_name || "-"}</p>
                  </div>
                  <div className="col-span-2">
                    <p className="text-xs text-white">{o.user_input}{o.user_zone ? ` (${o.user_zone})` : ""}</p>
                    {o.nickname && <p className="text-[10px] text-yellow-400 truncate">{o.nickname}</p>}
                  </div>
                  <div className="col-span-1 text-right">
                    <p className="text-xs font-bold text-white">Rp{Number(o.price).toLocaleString("id-ID")}</p>
                    {o.discount_amount > 0 && <p className="text-[9px] text-red-400 line-through">Rp{Number(o.original_price).toLocaleString("id-ID")}</p>}
                  </div>
                  <div className="col-span-1 text-center">
                    <span className={`inline-block px-2 py-0.5 rounded-full text-[9px] font-bold ${sb.bg} ${sb.text}`}>{sb.label}</span>
                  </div>
                  <div className="col-span-2 flex items-center justify-center gap-1.5">
                    {o.vip_trxid && (
                      <button onClick={() => checkVipStatus(o.id)} disabled={checkingId === o.id}
                        className="px-2 py-1 rounded-lg bg-blue-500/10 text-blue-400 text-[9px] font-bold hover:bg-blue-500/20">
                        {checkingId === o.id ? <Loader2 size={10} className="animate-spin" /> : "Cek VIP"}
                      </button>
                    )}
                    {o.phone && (
                      <a href={`https://wa.me/${o.phone.replace(/^0/, "62")}`} target="_blank" rel="noopener noreferrer"
                        className="p-1 rounded-lg bg-green-500/10 text-green-400 hover:bg-green-500/20">
                        <MessageCircle size={10} />
                      </a>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
        <Pagination />
      </div>

      {/* Mobile Card List */}
      <div className="md:hidden space-y-2">
        {loading ? (
          <div className="text-center py-12 text-muted"><Loader2 className="inline animate-spin mr-2" size={16} />Memuat...</div>
        ) : orders.length === 0 ? (
          <div className="text-center py-12 text-muted text-xs">Tidak ada pesanan</div>
        ) : (
          <>
            {orders.map((o) => {
              const sb = statusBadge(o.fulfill_status);
              return (
                <div key={o.id} className="bg-dark-surface rounded-xl border border-dark-border p-3.5 space-y-2">
                  {/* Top row: invoice + status */}
                  <div className="flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2 min-w-0">
                      <p className="text-xs font-bold text-white truncate">{o.invoice_no}</p>
                      <span className={`inline-block px-2 py-0.5 rounded-full text-[8px] font-bold shrink-0 ${sb.bg} ${sb.text}`}>{sb.label}</span>
                    </div>
                    <span className={`text-[9px] font-bold shrink-0 ${o.payment_status === "PAID" ? "text-green-400" : o.payment_status === "EXPIRED" ? "text-red-400" : "text-yellow-400"}`}>{o.payment_status}</span>
                  </div>

                  {/* Product info */}
                  <div>
                    <p className="text-[11px] font-medium text-white">{o.game_name}</p>
                    <p className="text-[10px] text-muted truncate">{o.product?.product_name || "-"}</p>
                  </div>

                  {/* Bottom row: ID + price + date */}
                  <div className="flex items-end justify-between gap-2">
                    <div className="min-w-0">
                      <p className="text-[10px] text-muted">ID: <span className="text-white">{o.user_input}{o.user_zone ? ` (${o.user_zone})` : ""}</span></p>
                      {o.nickname && <p className="text-[10px] text-yellow-400 truncate">{o.nickname}</p>}
                      <p className="text-[9px] text-muted/60 mt-0.5">{new Date(o.createdAt || o.created_at).toLocaleDateString("id-ID", { day: "2-digit", month: "short", year: "numeric" })}</p>
                    </div>
                    <div className="text-right shrink-0">
                      <p className="text-xs font-bold text-white">Rp{Number(o.price).toLocaleString("id-ID")}</p>
                      {o.discount_amount > 0 && <p className="text-[9px] text-red-400 line-through">Rp{Number(o.original_price).toLocaleString("id-ID")}</p>}
                    </div>
                  </div>

                  {/* Actions */}
                  {(o.vip_trxid || o.phone) && (
                    <div className="flex items-center gap-2 pt-1 border-t border-dark-border/50">
                      {o.vip_trxid && (
                        <button onClick={() => checkVipStatus(o.id)} disabled={checkingId === o.id}
                          className="px-3 py-1.5 rounded-lg bg-blue-500/10 text-blue-400 text-[10px] font-bold hover:bg-blue-500/20 flex-1">
                          {checkingId === o.id ? "Loading..." : "Cek VIP Status"}
                        </button>
                      )}
                      {o.phone && (
                        <a href={`https://wa.me/${o.phone.replace(/^0/, "62")}`} target="_blank" rel="noopener noreferrer"
                          className="px-3 py-1.5 rounded-lg bg-green-500/10 text-green-400 text-[10px] font-bold hover:bg-green-500/20 flex items-center gap-1.5">
                          <MessageCircle size={10} /> WA
                        </a>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
            <div className="bg-dark-surface rounded-xl border border-dark-border overflow-hidden">
              <Pagination />
            </div>
          </>
        )}
      </div>
    </div>
  );
}
