import Link from "next/link";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { EmptyState, PageHeader, btn } from "@/components/ui";
import { fmtDateTime } from "@/lib/utils";
import { markAllNotificationsRead } from "../actions";

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

export default async function NotificationsPage() {
  const user = await requireUser();
  const notifications = await db.notification.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: "desc" },
    take: 50,
  });

  return (
    <div>
      <PageHeader
        title="Notifications"
        sub="Announcements, submission decisions, review assignments."
        action={
          <form action={markAllNotificationsRead}>
            <button className={btn.smSecondary}>Mark all read</button>
          </form>
        }
      />
      {notifications.length === 0 && <EmptyState title="All quiet" body="Nothing here yet." />}
      <div className="space-y-2">
        {notifications.map((n) => (
          <div
            key={n.id}
            className={`rounded-lg border px-4 py-3 ${n.readAt ? "border-zinc-800/60 bg-zinc-900/30" : "border-indigo-500/30 bg-indigo-500/5"}`}
          >
            <div className="flex items-center justify-between gap-3">
              <span className={`text-sm ${n.readAt ? "text-zinc-400" : "font-medium text-zinc-100"}`}>{n.title}</span>
              <span className="shrink-0 text-xs text-zinc-600">{fmtDateTime(n.createdAt)}</span>
            </div>
            {n.body && <p className="mt-0.5 text-sm text-zinc-500">{n.body}</p>}
            {n.link && <Link href={n.link} className="mt-1 inline-block text-xs font-medium text-indigo-600 hover:underline">Open →</Link>}
          </div>
        ))}
      </div>
    </div>
  );
}
