import { getTranslations, setRequestLocale } from "next-intl/server";
import { redirect } from "next/navigation";
import Link from "next/link";
import { connectDB } from "@/lib/db";
import { Notification } from "@/models/Notification";
import { getSessionClientId } from "@/lib/auth";
import { MarkAllReadButton } from "@/components/account/MarkAllReadButton";
import { AccountPageHeader } from "@/components/account/AccountPageHeader";

export const dynamic = "force-dynamic";

export default async function AccountNotificationsPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  setRequestLocale(locale);
  const t = await getTranslations({ locale, namespace: "notifications" });

  const clientId = await getSessionClientId();
  if (!clientId) redirect(`/${locale}/login`);

  await connectDB();
  const notifications = await Notification.find({ recipientId: clientId }).sort({ createdAt: -1 }).limit(100).lean();
  const unreadCount = notifications.filter((n) => !n.read).length;

  return (
    <div>
      <div className="flex max-w-2xl flex-col gap-6">
        <div>
          <AccountPageHeader
            eyebrow={t("eyebrow")}
            title={t("title")}
            subtitle={t("summary", { total: notifications.length, unread: unreadCount })}
          />
          {unreadCount > 0 && <MarkAllReadButton label={t("markAllRead")} />}
        </div>

        {notifications.length === 0 ? (
          <p className="text-sm text-[var(--rk-ink-muted)]">{t("empty")}</p>
        ) : (
          <div className="flex flex-col gap-2">
            {notifications.map((n) => (
              <Link
                key={String(n._id)}
                href={n.link || `/${locale}/account`}
                className={`flex items-start gap-3 rounded-xl border px-4 py-3 transition-colors hover:border-white/25 ${
                  n.read
                    ? "border-white/10 bg-[var(--rk-surface)]"
                    : "border-[var(--rk-accent)]/30 bg-[var(--rk-accent)]/[0.05]"
                }`}
              >
                <span
                  className={`mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full ${
                    n.read ? "bg-transparent" : "bg-[var(--rk-accent)]"
                  }`}
                />
                <div className="min-w-0">
                  <p className="text-sm text-[var(--rk-ink)]">{n.title}</p>
                  {n.body && <p className="text-xs text-[var(--rk-ink-muted)] mt-0.5">{n.body}</p>}
                  <p className="text-[0.65rem] text-[var(--rk-ink-muted)] mt-1">
                    {new Date(n.createdAt).toLocaleString(locale === "en" ? "en-GB" : "de-DE")}
                  </p>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
