"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/apiClient";
import { formatNaira, formatDateTime } from "@/lib/utils";

type Status = "ALL" | "SUCCESS" | "FAILED" | "PENDING";

interface AdminTransaction {
  id: string;
  amount: number;
  status: string;
  gatewayReference: string;
  createdAt: string;
  booking: {
    user: { fullName: string; email: string };
    package: { name: string };
  };
}

export default function AdminTransactionsPage() {
  const router = useRouter();
  const [transactions, setTransactions] = useState<AdminTransaction[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<Status>("ALL");
  const [page, setPage] = useState(1);
  const PAGE_SIZE = 25;

  useEffect(() => {
    setLoading(true);
    const q = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });
    if (filter !== "ALL") q.set("status", filter);
    apiFetch<{ transactions: AdminTransaction[]; total: number }>(`/admin/transactions?${q}`)
      .then((d) => { setTransactions(d.transactions); setTotal(d.total); })
      .catch((err) => { if (err?.status === 401 || err?.status === 403) router.replace("/admin/login"); })
      .finally(() => setLoading(false));
  }, [page, filter, router]);

  async function exportCSV() {
    const q = new URLSearchParams();
    if (filter !== "ALL") q.set("status", filter);
    q.set("format", "csv");
    try {
      const res = await fetch(`/api/admin/transactions?${q}`, {
        headers: { Authorization: `Bearer ${(window as any).__AT ?? ""}` },
      });
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a"); a.href = url;
      a.download = `transactions-${new Date().toISOString().split("T")[0]}.csv`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {}
  }

  const statusColor = (s: string) => s === "SUCCESS" ? "#B8952A" : s === "FAILED" ? "#EF4444" : "#F59E0B";

  return (
    <div className="p-6 max-w-7xl">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-[#111111] font-black text-2xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Transactions</h1>
          <p className="text-[#6B7280] text-sm mt-0.5">{total} transactions</p>
        </div>
        <button onClick={exportCSV}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold border border-gray-200 text-[#6B7280] hover:bg-gray-50 transition-colors">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>
          </svg>
          Export CSV
        </button>
      </div>

      {/* Filter tabs */}
      <div className="flex gap-2 mb-4">
        {(["ALL", "SUCCESS", "PENDING", "FAILED"] as Status[]).map((f) => (
          <button key={f} onClick={() => { setFilter(f); setPage(1); }}
            className="px-4 py-2 rounded-full text-xs font-semibold transition-all"
            style={filter === f
              ? { background: "#1C2472", color: "white" }
              : { background: "white", color: "#6B7280", border: "1px solid #E5E7EB" }}>
            {f === "ALL" ? "All" : f.charAt(0) + f.slice(1).toLowerCase()}
          </button>
        ))}
      </div>

      <div className="bg-white rounded-2xl overflow-hidden" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr style={{ background: "#F8F8F8", borderBottom: "1px solid #E5E7EB" }}>
                {["Date", "Customer", "Package", "Amount", "Status", "Reference"].map((h) => (
                  <th key={h} className="px-5 py-3 text-left text-[10px] font-bold text-[#9CA3AF] uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {loading ? Array(8).fill(0).map((_, i) => (
                <tr key={i}>
                  {Array(6).fill(0).map((_, j) => (
                    <td key={j} className="px-5 py-3.5"><div className="h-4 bg-gray-100 rounded animate-pulse" /></td>
                  ))}
                </tr>
              )) : transactions.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-5 py-12 text-center text-[#6B7280] text-sm">No transactions found</td>
                </tr>
              ) : transactions.map((tx) => (
                <tr key={tx.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-5 py-3.5 text-[#9CA3AF] text-xs whitespace-nowrap">{formatDateTime(tx.createdAt)}</td>
                  <td className="px-5 py-3.5">
                    <p className="font-semibold text-[#111111] text-sm">{tx.booking?.user?.fullName}</p>
                    <p className="text-[#9CA3AF] text-xs">{tx.booking?.user?.email}</p>
                  </td>
                  <td className="px-5 py-3.5 text-[#6B7280] text-sm">{tx.booking?.package?.name}</td>
                  <td className="px-5 py-3.5 font-bold text-[#111111]">{formatNaira(tx.amount)}</td>
                  <td className="px-5 py-3.5">
                    <span className="text-[10px] font-bold px-2 py-0.5 rounded-full"
                      style={{ background: `${statusColor(tx.status)}15`, color: statusColor(tx.status) }}>
                      {tx.status}
                    </span>
                  </td>
                  <td className="px-5 py-3.5 font-mono text-[#9CA3AF] text-xs">{tx.gatewayReference.slice(-16)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {total > PAGE_SIZE && (
          <div className="flex items-center justify-between px-5 py-4 border-t border-gray-50">
            <p className="text-[#9CA3AF] text-xs">Showing {(page - 1) * PAGE_SIZE + 1}–{Math.min(page * PAGE_SIZE, total)} of {total}</p>
            <div className="flex gap-2">
              <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page === 1}
                className="px-3 py-1.5 rounded-lg text-xs font-semibold border border-gray-200 text-[#6B7280] disabled:opacity-40 hover:bg-gray-50">
                Prev
              </button>
              <button onClick={() => setPage((p) => p + 1)} disabled={page * PAGE_SIZE >= total}
                className="px-3 py-1.5 rounded-lg text-xs font-semibold border border-gray-200 text-[#6B7280] disabled:opacity-40 hover:bg-gray-50">
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
