import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise } from "@/lib/format";
import { parseDateRange, dateRangeWhere } from "@/lib/reports";
import ReportsTabs from "@/components/admin/ReportsTabs";
import ReportDateFilter from "@/components/admin/ReportDateFilter";

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

export default async function AdminPaymentReportPage({
  searchParams,
}: {
  searchParams: Promise<{ from?: string; to?: string }>;
}) {
  const params = await searchParams;
  const range = parseDateRange(params);
  const createdAt = dateRangeWhere(range);

  const orders = await prisma.order.findMany({
    where: { status: "paid", ...(createdAt ? { createdAt } : {}) },
    select: { total: true, paymentMethod: true, refundedAmount: true },
  });

  const collected = orders.reduce((sum, o) => sum + o.total, 0);
  const refunded = orders.reduce((sum, o) => sum + o.refundedAmount, 0);

  const byMethod = new Map<string, { count: number; amount: number }>();
  for (const o of orders) {
    const key = o.paymentMethod ?? "unknown";
    const row = byMethod.get(key) ?? { count: 0, amount: 0 };
    row.count += 1;
    row.amount += o.total;
    byMethod.set(key, row);
  }
  const methodRows = [...byMethod.entries()].sort((a, b) => b[1].amount - a[1].amount);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Payment Report</h1>
      <p className="mt-1 text-sm text-stone-500">
        A summary view. For the line-item ledger, transaction IDs, and refund actions, see{" "}
        <Link href="/iv-manage-84x2/payments" className="text-rose-700 hover:underline">
          Payments
        </Link>
        .
      </p>

      <ReportsTabs active="/iv-manage-84x2/reports/payments" />
      <ReportDateFilter action="/iv-manage-84x2/reports/payments" from={range.fromStr} to={range.toStr} />

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
        <div className="rounded-lg border border-rose-100 bg-white p-4">
          <p className="text-xs uppercase text-stone-500">Collected</p>
          <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(collected)}</p>
        </div>
        <div className="rounded-lg border border-rose-100 bg-white p-4">
          <p className="text-xs uppercase text-stone-500">Refunded</p>
          <p className="mt-1 text-xl font-bold text-stone-800">{formatPaise(refunded)}</p>
        </div>
        <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4">
          <p className="text-xs uppercase text-emerald-700">Net</p>
          <p className="mt-1 text-xl font-bold text-emerald-800">{formatPaise(collected - refunded)}</p>
        </div>
      </div>

      <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {methodRows.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No paid orders in this range.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Method</th>
                <th className="p-3">Payments</th>
                <th className="p-3">Amount</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {methodRows.map(([method, row]) => (
                <tr key={method}>
                  <td className="p-3 font-medium text-stone-800">{METHOD_LABELS[method] ?? (method === "unknown" ? "Unknown / not recorded" : method)}</td>
                  <td className="p-3 text-stone-600">{row.count}</td>
                  <td className="p-3 text-stone-600">{formatPaise(row.amount)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
