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";

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

  const coupons = await prisma.coupon.findMany({ orderBy: { createdAt: "desc" } });
  const orders = await prisma.order.findMany({
    where: { status: "paid", couponCode: { not: null }, ...(createdAt ? { createdAt } : {}) },
    select: { couponCode: true, total: true, discountAmount: true },
  });

  const byCoupon = new Map<string, { orders: number; discountGiven: number; revenue: number }>();
  for (const o of orders) {
    const code = o.couponCode!;
    const row = byCoupon.get(code) ?? { orders: 0, discountGiven: 0, revenue: 0 };
    row.orders += 1;
    row.discountGiven += o.discountAmount;
    row.revenue += o.total;
    byCoupon.set(code, row);
  }

  const rows = coupons.map((c) => ({
    ...c,
    ordersInRange: byCoupon.get(c.code)?.orders ?? 0,
    discountGiven: byCoupon.get(c.code)?.discountGiven ?? 0,
    revenue: byCoupon.get(c.code)?.revenue ?? 0,
  }));

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Coupon Report</h1>
      <p className="mt-1 text-sm text-stone-500">
        Usage and discount given per coupon (paid orders in range). Lifetime use counts come from{" "}
        the coupon record itself and aren&apos;t affected by the date filter.
      </p>

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

      {rows.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No coupons yet.</p>
      ) : (
        <div className="overflow-hidden rounded-lg border border-rose-100 bg-white">
          <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">Code</th>
                <th className="p-3">Lifetime uses</th>
                <th className="p-3">Orders in range</th>
                <th className="p-3">Discount given (range)</th>
                <th className="p-3">Revenue (range)</th>
                <th className="p-3">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {rows.map((c) => (
                <tr key={c.id}>
                  <td className="p-3 font-mono font-medium text-stone-800">{c.code}</td>
                  <td className="p-3 text-stone-600">
                    {c.usedCount}
                    {c.maxUses ? ` / ${c.maxUses}` : ""}
                  </td>
                  <td className="p-3 text-stone-600">{c.ordersInRange}</td>
                  <td className="p-3 text-stone-600">{formatPaise(c.discountGiven)}</td>
                  <td className="p-3 text-stone-600">{formatPaise(c.revenue)}</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${c.active ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {c.active ? "Active" : "Inactive"}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
