import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Card, PageHeader, StatCard, StatusBadge, btn } from "@/components/ui";
import { dayKey, fmtDateTime, formatMoney } from "@/lib/utils";
import { refundPayment } from "../actions";

export const metadata = { title: "Finance" };

export default async function FinancePage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  await requireConfAccess(id, "finance.view");

  const [confirmed, payments, coupons, ticketTypes] = await Promise.all([
    db.registration.findMany({ where: { conferenceId: id, status: "CONFIRMED" }, include: { ticketType: true } }),
    db.payment.findMany({
      where: { registration: { conferenceId: id } },
      orderBy: { createdAt: "desc" },
      take: 60,
      include: { registration: true },
    }),
    db.coupon.findMany({ where: { conferenceId: id }, orderBy: { usedCount: "desc" } }),
    db.ticketType.findMany({ where: { conferenceId: id } }),
  ]);

  const revenue = confirmed.reduce((s, r) => s + r.amount, 0);
  const refunded = payments.filter((p) => p.status === "REFUNDED").reduce((s, p) => s + p.amount, 0);
  const failed = payments.filter((p) => p.status === "FAILED").length;
  const discountGiven = confirmed.reduce((s, r) => s + Math.max(0, r.ticketType.price - r.amount), 0);

  // revenue by ticket type
  const byTicket = ticketTypes
    .map((t) => ({
      name: t.name,
      count: confirmed.filter((r) => r.ticketTypeId === t.id).length,
      total: confirmed.filter((r) => r.ticketTypeId === t.id).reduce((s, r) => s + r.amount, 0),
    }))
    .filter((x) => x.count > 0)
    .sort((a, b) => b.total - a.total);
  const maxTicket = Math.max(1, ...byTicket.map((x) => x.total));

  // revenue by day (successful payments + free confirmations approximated by registration date)
  const byDayMap = new Map<string, number>();
  for (const r of confirmed) {
    const k = dayKey(r.createdAt);
    byDayMap.set(k, (byDayMap.get(k) ?? 0) + r.amount);
  }
  const byDay = [...byDayMap.entries()].sort(([a], [b]) => a.localeCompare(b)).slice(-14);
  const maxDay = Math.max(1, ...byDay.map(([, v]) => v));

  return (
    <main>
      <PageHeader
        title="Finance"
        sub="Confirmed revenue, payments, refunds and coupon performance."
        action={
          <div className="flex gap-2">
            <a href={`/api/v1/conferences/${id}/reports/revenue`} className={btn.secondary}>⬇ Revenue CSV</a>
            <a href={`/api/v1/conferences/${id}/reports/payments`} className={btn.secondary}>⬇ Payments CSV</a>
          </div>
        }
      />

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label="Confirmed revenue" value={formatMoney(revenue)} accent="text-emerald-600" sub={`${confirmed.length} paid/confirmed registrations`} />
        <StatCard label="Discounts given" value={formatMoney(discountGiven)} sub="via coupons & price differences" />
        <StatCard label="Refunded" value={formatMoney(refunded)} accent="text-orange-600" sub={`${payments.filter((p) => p.status === "REFUNDED").length} refunds`} />
        <StatCard label="Failed payments" value={failed} accent={failed > 0 ? "text-red-600" : "text-zinc-100"} sub="attempts that didn't complete" />
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        <Card className="p-5">
          <h2 className="text-sm font-semibold text-zinc-300">Revenue by ticket type</h2>
          <div className="mt-4 space-y-3">
            {byTicket.length === 0 && <p className="text-sm text-zinc-500">No confirmed revenue yet.</p>}
            {byTicket.map((t) => (
              <div key={t.name}>
                <div className="flex justify-between text-sm">
                  <span className="font-medium text-zinc-200">{t.name} <span className="text-xs text-zinc-500">× {t.count}</span></span>
                  <span className="font-semibold tabular-nums text-zinc-200">{formatMoney(t.total)}</span>
                </div>
                <div className="mt-1 h-2 overflow-hidden rounded-full bg-zinc-800/70">
                  <div className="h-full rounded-full bg-gradient-to-r from-indigo-500 to-violet-500" style={{ width: `${(t.total / maxTicket) * 100}%` }} />
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card className="p-5">
          <h2 className="text-sm font-semibold text-zinc-300">Revenue by day (last 14 active days)</h2>
          {byDay.length === 0 ? (
            <p className="mt-4 text-sm text-zinc-500">Nothing yet.</p>
          ) : (
            <div className="mt-4 flex h-36 items-end gap-1.5">
              {byDay.map(([day, v]) => (
                <div key={day} className="group flex flex-1 flex-col items-center gap-1" title={`${day}: ${formatMoney(v)}`}>
                  <div className="w-full rounded-t-md bg-gradient-to-t from-emerald-500 to-teal-400 transition group-hover:brightness-110" style={{ height: `${Math.max(6, (v / maxDay) * 100)}%` }} />
                  <span className="text-[9px] tabular-nums text-zinc-600">{day.slice(5)}</span>
                </div>
              ))}
            </div>
          )}
          <h3 className="mt-5 text-xs font-semibold uppercase tracking-wider text-zinc-500">Coupon usage</h3>
          <div className="mt-2 space-y-1.5 text-sm">
            {coupons.length === 0 && <p className="text-zinc-500">No coupons created.</p>}
            {coupons.map((c) => (
              <div key={c.id} className="flex justify-between">
                <span className="font-mono font-semibold text-zinc-300">{c.code}</span>
                <span className="text-zinc-500">
                  {c.discountType === "PERCENT" ? `${c.value}% off` : `${formatMoney(c.value)} off`} · used {c.usedCount}{c.maxUses != null ? `/${c.maxUses}` : ""}
                </span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card className="mt-4 p-5">
        <h2 className="text-sm font-semibold text-zinc-300">Payments</h2>
        <div className="mt-3 overflow-x-auto">
          <table className="w-full min-w-[720px] text-sm">
            <thead>
              <tr className="border-b border-zinc-800 text-left text-xs uppercase tracking-wider text-zinc-500">
                <th className="py-2 pr-4">Txn</th>
                <th className="py-2 pr-4">Attendee</th>
                <th className="py-2 pr-4">Amount</th>
                <th className="py-2 pr-4">Gateway</th>
                <th className="py-2 pr-4">Status</th>
                <th className="py-2 pr-4">At</th>
                <th className="py-2 text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-800/70">
              {payments.length === 0 && <tr><td colSpan={7} className="py-8 text-center text-zinc-500">No payments yet.</td></tr>}
              {payments.map((p) => (
                <tr key={p.id}>
                  <td className="py-2.5 pr-4 font-mono text-xs text-zinc-400">{p.txnId}</td>
                  <td className="py-2.5 pr-4">
                    <div className="font-medium text-zinc-200">{p.registration.name}</div>
                    <div className="text-xs text-zinc-500">{p.registration.regCode}</div>
                  </td>
                  <td className="py-2.5 pr-4 tabular-nums font-semibold text-zinc-200">{formatMoney(p.amount)}</td>
                  <td className="py-2.5 pr-4 text-xs text-zinc-500">{p.gateway}</td>
                  <td className="py-2.5 pr-4"><StatusBadge status={p.status} /></td>
                  <td className="py-2.5 pr-4 text-xs text-zinc-500">{fmtDateTime(p.createdAt)}</td>
                  <td className="py-2.5 text-right">
                    {p.status === "SUCCESS" && (
                      <details className="relative inline-block text-left">
                        <summary className="cursor-pointer list-none rounded-lg border border-white/70 bg-white/60 px-2.5 py-1 text-xs font-medium text-orange-600 backdrop-blur [&::-webkit-details-marker]:hidden">Refund…</summary>
                        <form action={refundPayment.bind(null, id, p.id)} className="absolute right-0 z-10 mt-1 w-64 rounded-xl border border-orange-200 bg-white/95 p-3 text-left shadow-xl backdrop-blur">
                          <p className="text-xs text-zinc-500">Refunds {formatMoney(p.amount)} and <strong>cancels the registration</strong>. The attendee is emailed.</p>
                          <button className="mt-2 w-full rounded-lg bg-orange-500 px-3 py-1.5 text-xs font-bold text-white hover:bg-orange-600">Confirm refund</button>
                        </form>
                      </details>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </main>
  );
}
