import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import PaymentsTabs from "@/components/admin/PaymentsTabs";
import ScrollableTable from "@/components/admin/ScrollableTable";
import StatusBadge from "@/components/admin/StatusBadge";

const METHOD_LABELS: Record<string, string> = {
  card: "Card",
  upi: "UPI",
  netbanking: "Netbanking",
  wallet: "Wallet",
  emi: "EMI",
};

export default async function AdminPaymentTransactionsPage() {
  const orders = await prisma.order.findMany({ orderBy: { createdAt: "desc" } });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Payment Transactions</h1>
      <p className="mt-1 text-sm text-stone-500">Every checkout attempt — pending, paid, or failed — in one log.</p>

      <PaymentsTabs active="/iv-manage-84x2/payments/transactions" />

      {orders.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No transactions yet.</p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[900px] text-sm">
            <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Order</th>
                <th className="p-3">Customer</th>
                <th className="p-3">Amount</th>
                <th className="p-3">Method</th>
                <th className="p-3">Razorpay Payment ID</th>
                <th className="p-3">Status</th>
                <th className="p-3">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {orders.map((o) => (
                <tr key={o.id}>
                  <td className="whitespace-nowrap p-3">
                    <Link href={`/iv-manage-84x2/orders/${o.id}`} className="font-medium text-rose-700 hover:underline">
                      {o.orderNumber}
                    </Link>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{o.customerName}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(o.total)}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">
                    {o.paymentMethod ? METHOD_LABELS[o.paymentMethod] ?? o.paymentMethod : "—"}
                  </td>
                  <td className="whitespace-nowrap p-3 font-mono text-xs text-stone-500">{o.razorpayPaymentId ?? "—"}</td>
                  <td className="whitespace-nowrap p-3">
                    <StatusBadge status={o.status} />
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(o.createdAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
