import { db } from "@/lib/db";
import { can, requireConfAccess, type Action } from "@/lib/rbac";
import { Card, PageHeader } from "@/components/ui";

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

const REPORTS: { type: string; icon: string; title: string; desc: string; perm: Action; count?: string }[] = [
  { type: "registrations", icon: "🎟️", title: "Registrations", desc: "Every registration with contact, pass, payment status and check-in flag.", perm: "registrations.export" },
  { type: "checkins", icon: "✅", title: "Attendance / check-ins", desc: "Timestamped check-in log — conference and session level.", perm: "registrations.export" },
  { type: "payments", icon: "💳", title: "Payments", desc: "All payment attempts with gateway, status and transaction IDs.", perm: "finance.view" },
  { type: "revenue", icon: "📈", title: "Revenue & discounts", desc: "Per-registration list price, paid amount, discount and coupon.", perm: "finance.view" },
  { type: "sessions", icon: "🗓️", title: "Sessions", desc: "Full agenda with tracks, halls, speakers, check-ins and bookmarks.", perm: "agenda.manage" },
  { type: "speakers", icon: "🎤", title: "Speakers", desc: "Speaker roster with type, affiliation and assigned sessions.", perm: "speakers.manage" },
  { type: "submissions", icon: "📄", title: "Submissions & reviews", desc: "CFP pipeline with statuses, review counts and average scores.", perm: "submissions.manage" },
  { type: "sponsors", icon: "🤝", title: "Sponsors", desc: "Sponsors with tier, commitment amount, booth and contacts.", perm: "sponsors.manage" },
  { type: "certificates", icon: "🏅", title: "Certificates", desc: "Issued certificates with verification IDs and recipients.", perm: "certificates.manage" },
  { type: "feedback", icon: "⭐", title: "Feedback", desc: "Conference and session ratings with comments.", perm: "content.manage" },
];

export default async function ReportsPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { membership } = await requireConfAccess(id, "registrations.export");

  const [regs, checkins, payments, sessions, speakers, submissions, sponsors, certs, feedback] = await Promise.all([
    db.registration.count({ where: { conferenceId: id } }),
    db.checkIn.count({ where: { registration: { conferenceId: id } } }),
    db.payment.count({ where: { registration: { conferenceId: id } } }),
    db.session.count({ where: { conferenceId: id } }),
    db.speaker.count({ where: { conferenceId: id } }),
    db.submission.count({ where: { conferenceId: id, status: { not: "DRAFT" } } }),
    db.sponsor.count({ where: { conferenceId: id } }),
    db.certificate.count({ where: { conferenceId: id } }),
    db.feedback.count({ where: { conferenceId: id } }),
  ]);
  const counts: Record<string, number> = {
    registrations: regs, checkins, payments, revenue: regs, sessions, speakers,
    submissions, sponsors, certificates: certs, feedback,
  };
  const visible = REPORTS.filter((r) => can(membership, r.perm));

  return (
    <main>
      <PageHeader title="Reports" sub="Downloadable CSV exports — open directly in Excel or Google Sheets. Each report respects your role's permissions." />
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
        {visible.map((r) => (
          <a key={r.type} href={`/api/v1/conferences/${id}/reports/${r.type}`} className="group">
            <Card className="fx-lift h-full p-5">
              <div className="flex items-start justify-between">
                <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-indigo-500/15 to-fuchsia-500/15 text-lg">{r.icon}</span>
                <span className="rounded-full bg-zinc-800/70 px-2 py-0.5 text-[11px] font-semibold tabular-nums text-zinc-400">{counts[r.type] ?? 0} rows</span>
              </div>
              <h2 className="mt-3 font-bold text-zinc-100">{r.title}</h2>
              <p className="mt-1 text-sm text-zinc-500">{r.desc}</p>
              <div className="mt-3 text-xs font-semibold text-indigo-600 group-hover:underline">⬇ Download CSV</div>
            </Card>
          </a>
        ))}
      </div>
    </main>
  );
}
