import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule, rangeWindow } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { btn, Card, EmptyState, PageHeader, input } from "@/components/ui";
import { ORG_REPORT_TYPES, buildOrgReport } from "@/lib/org-reports";

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

export default async function ReportsPage({
  searchParams,
}: {
  searchParams: Promise<{ type?: string; conf?: string; range?: string; from?: string; to?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "reports")) {
    return <EmptyState title="No access" body="Reports are not part of your role." />;
  }
  const org = ctx.org;
  const sp = await searchParams;
  const type = sp.type && ORG_REPORT_TYPES.some((t) => t.key === sp.type) ? sp.type : null;

  const conferences = await db.conference.findMany({ where: { orgId: org.id }, orderBy: { startAt: "desc" }, select: { id: true, name: true } });
  const conf = sp.conf && conferences.some((c) => c.id === sp.conf) ? sp.conf : undefined;
  const { start, end } = rangeWindow(sp.range, sp.from, sp.to);

  const report = type ? await buildOrgReport(type, { orgId: org.id, conf, start, end }) : null;
  const active = ORG_REPORT_TYPES.find((t) => t.key === type);

  const exportQS = new URLSearchParams({
    ...(type ? { type } : {}),
    ...(conf ? { conf } : {}),
    ...(sp.range ? { range: sp.range } : {}),
    ...(sp.from ? { from: sp.from } : {}),
    ...(sp.to ? { to: sp.to } : {}),
  }).toString();

  return (
    <main>
      <PageHeader
        title="📊 Reports & Analytics"
        sub={`Organization-wide reporting for ${org.name} — filter by conference and date, preview, then export.`}
      />

      {/* Report type cards */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">
        {ORG_REPORT_TYPES.map((t) => (
          <Link
            key={t.key}
            href={`/dashboard/reports?type=${t.key}${conf ? `&conf=${conf}` : ""}${sp.range ? `&range=${sp.range}` : ""}`}
            className={`rounded-2xl border p-4 backdrop-blur-xl transition ${
              type === t.key
                ? "border-indigo-400/70 bg-indigo-500/10 shadow-lg shadow-indigo-500/10"
                : "border-white/70 bg-white/60 hover:border-indigo-300/70"
            }`}
          >
            <div className="text-xl">{t.icon}</div>
            <div className="mt-1.5 text-sm font-bold text-zinc-100">{t.label}</div>
            <div className="mt-1 text-[11px] leading-relaxed text-zinc-500">{t.desc}</div>
          </Link>
        ))}
      </div>

      {/* Filters + preview */}
      {type && report && (
        <Card className="mt-6 p-5">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h3 className="text-sm font-bold text-zinc-100">{active?.icon} {active?.label} <span className="font-normal text-zinc-500">({report.rows.length} rows)</span></h3>
            <div className="flex flex-wrap items-center gap-2">
              <form className="flex flex-wrap items-center gap-2" action="/dashboard/reports">
                <input type="hidden" name="type" value={type} />
                <select name="conf" defaultValue={conf ?? ""} className={`${input} !w-52 !py-1.5 text-xs`} aria-label="Conference">
                  <option value="">All conferences</option>
                  {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
                <select name="range" defaultValue={sp.range ?? ""} className={`${input} !w-36 !py-1.5 text-xs`} aria-label="Range">
                  <option value="">All time</option>
                  <option value="month">This Month</option>
                  <option value="quarter">This Quarter</option>
                  <option value="year">This Year</option>
                </select>
                <button className={btn.smSecondary}>Apply</button>
              </form>
              <a href={`/dashboard/reports/export?${exportQS}`} className={btn.sm}>⬇ Export CSV</a>
            </div>
          </div>
          <p className="mt-1 text-xs text-zinc-500">CSV opens in Excel / Google Sheets; use your browser's print dialog for PDF.</p>

          {report.rows.length === 0 ? (
            <div className="mt-4"><EmptyState title="No data for these filters" /></div>
          ) : (
            <div className="mt-4 overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                    {report.header.map((h) => <th key={h} className="whitespace-nowrap px-3 py-2">{h}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {report.rows.slice(0, 50).map((row, i) => (
                    <tr key={i} className="border-b border-zinc-800/40">
                      {row.map((cell, j) => (
                        <td key={j} className="max-w-[220px] truncate whitespace-nowrap px-3 py-2 text-zinc-300">{String(cell)}</td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
              {report.rows.length > 50 && (
                <p className="mt-2 text-xs text-zinc-500">Previewing first 50 of {report.rows.length} rows — export the CSV for the full report.</p>
              )}
            </div>
          )}
        </Card>
      )}
      {!type && (
        <p className="mt-5 text-sm text-zinc-500">Pick a report above to preview it here.</p>
      )}
    </main>
  );
}
