import Link from "next/link";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getOrgContext } from "@/lib/org";
import { Card, EmptyState, PageHeader, StatCard, btn } from "@/components/ui";
import { fmtDateTime } from "@/lib/utils";
import { markAllReadAction, markOneReadAction } from "./actions";
import { PushToggle } from "@/components/push-toggle";

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

export default async function DashboardNotificationsPage() {
  const user = await requireUser();
  const ctx = await getOrgContext();
  const [notifications, unread, activity] = await Promise.all([
    db.notification.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 100 }),
    db.notification.count({ where: { userId: user.id, readAt: null } }),
    ctx?.org
      ? db.auditLog.findMany({
          where: { OR: [{ conference: { orgId: ctx.org.id } }, { user: { orgMembers: { some: { orgId: ctx.org.id } } } }] },
          orderBy: { createdAt: "desc" },
          take: 30,
          include: { user: { select: { name: true } }, conference: { select: { name: true } } },
        })
      : [],
  ]);

  const humanize = (action: string) =>
    action.replace(/[._]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());

  // group by day for a detailed, scannable feed
  const groups = new Map<string, typeof notifications>();
  for (const n of notifications) {
    const day = n.createdAt.toLocaleDateString("en-IN", { day: "numeric", month: "long", year: "numeric", timeZone: "Asia/Kolkata" });
    if (!groups.has(day)) groups.set(day, []);
    groups.get(day)!.push(n);
  }

  return (
    <main className="mx-auto max-w-3xl px-4 py-8">
      <PageHeader
        title="🔔 Notifications"
        sub="Volunteer activity, submissions, and platform events — newest first."
        action={
          <div className="flex flex-wrap items-center gap-2">
            <PushToggle />
            {unread > 0 && (
              <form action={markAllReadAction}>
                <button className={btn.secondary}>Mark all {unread} read</button>
              </form>
            )}
          </div>
        }
      />

      <div className="mb-6 grid grid-cols-2 gap-3">
        <StatCard label="Unread" value={unread} accent={unread > 0 ? "text-indigo-600" : "text-zinc-100"} />
        <StatCard label="Total (last 100)" value={notifications.length} />
      </div>

      {notifications.length === 0 && (
        <EmptyState title="All quiet" body="When volunteers act on your conferences or submissions arrive, you'll see it here." />
      )}

      <div className="space-y-6">
        {[...groups.entries()].map(([day, list]) => (
          <section key={day}>
            <h2 className="mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500">{day}</h2>
            <div className="space-y-2">
              {list.map((n) => (
                <Card
                  key={n.id}
                  className={`p-4 ${n.readAt ? "opacity-70" : "border-indigo-300/70 shadow-[0_8px_32px_rgba(99,102,241,0.15)]"}`}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <div className={`text-sm ${n.readAt ? "text-zinc-400" : "font-semibold text-zinc-100"}`}>{n.title}</div>
                      {n.body && <div className="mt-0.5 text-sm text-zinc-500">{n.body}</div>}
                      <div className="mt-1.5 flex items-center gap-3 text-xs">
                        <span className="text-zinc-600">{fmtDateTime(n.createdAt)}</span>
                        {n.link && <Link href={n.link} className="font-medium text-indigo-600 hover:underline">Open →</Link>}
                      </div>
                    </div>
                    {!n.readAt && (
                      <form action={markOneReadAction.bind(null, n.id)}>
                        <button className="shrink-0 rounded-md border border-white/70 bg-white/60 px-2 py-1 text-[11px] text-zinc-400 transition hover:bg-white/90" title="Mark read">
                          ✓ Read
                        </button>
                      </form>
                    )}
                  </div>
                </Card>
              ))}
            </div>
          </section>
        ))}
      </div>

      {/* Activity log */}
      {activity.length > 0 && (
        <section className="mt-10">
          <h2 className="text-base font-bold text-zinc-100">🧾 Activity Log</h2>
          <p className="mt-1 text-sm text-zinc-500">Recent actions across your organization — who did what, where.</p>
          <Card className="mt-3 divide-y divide-zinc-800/30">
            {activity.map((a) => (
              <div key={a.id} className="flex items-start justify-between gap-3 px-4 py-2.5">
                <div className="min-w-0 text-sm text-zinc-300">
                  <span className="font-semibold text-zinc-100">{a.user?.name ?? "System"}</span>{" "}
                  <span className="text-zinc-400">{humanize(a.action)}</span>
                  {a.conference && <span className="text-zinc-500"> · {a.conference.name}</span>}
                </div>
                <span className="shrink-0 text-xs text-zinc-600">{fmtDateTime(a.createdAt)}</span>
              </div>
            ))}
          </Card>
        </section>
      )}
    </main>
  );
}
