import type { Metadata } from "next";
import { Bell } from "lucide-react";
import { requireUser } from "@/lib/auth/rbac";
import {
  countUnread,
  listNotifications,
  rollupNotificationsByType,
} from "@/lib/queries/notifications";
import { PageHeader, StatCard } from "@/components/ui/page-header";
import { routeCrumbs } from "@/lib/breadcrumbs";
import { EmptyState } from "@/components/ui/empty-state";
import { Badge } from "@/components/ui/badge";
import { NotificationItem } from "@/components/notifications/notification-item";
import { NotificationTabs } from "@/components/notifications/notification-tabs";
import { MarkAllReadButton } from "@/components/notifications/mark-all-read-button";
import { NOTIFICATION_TONE } from "@/lib/labels";

export const metadata: Metadata = {
  title: "Notifikasi",
  description: "Kotak masuk pemberitahuan akunmu.",
};

const TYPE_LABELS: Record<string, string> = {
  INFO: "Informasi",
  SUCCESS: "Berhasil",
  WARNING: "Peringatan",
  ERROR: "Galat",
  GRADE: "Nilai",
  ASSIGNMENT: "Tugas",
  ANNOUNCEMENT: "Pengumuman",
  ACHIEVEMENT: "Pencapaian",
};

export default async function NotificationsPage({
  searchParams,
}: {
  searchParams: Promise<{ filter?: string }>;
}) {
  const user = await requireUser("/dashboard/notifications");
  const params = await searchParams;
  const unreadOnly = params.filter === "unread";

  const [notifications, unreadCount, rollup] = await Promise.all([
    listNotifications(user.id, { unreadOnly }),
    countUnread(user.id),
    rollupNotificationsByType(user.id),
  ]);

  const totalCount = rollup.reduce((sum, row) => sum + row.total, 0);

  return (
    <div className="space-y-6">
      <PageHeader
        folio="TC/LMS-23"
        crumbs={routeCrumbs("/dashboard/notifications", "Notifikasi")}
        title="Notifikasi"
        description="Semua pemberitahuan tentang tugas, nilai, dan pengumuman."
        actions={<MarkAllReadButton disabled={unreadCount === 0} />}
      />

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label="Belum dibaca"
          value={unreadCount}
          hint={unreadCount === 0 ? "Semua sudah dibaca" : "Menunggu perhatianmu"}
          tone={unreadCount > 0 ? "warning" : "success"}
          icon={<Bell className="size-5" />}
        />
        {rollup.slice(0, 3).map((row) => (
          <StatCard
            key={row.type}
            label={TYPE_LABELS[row.type] ?? row.type}
            value={row.total}
            hint={row.unread > 0 ? `${row.unread} belum dibaca` : "Sudah dibaca semua"}
            tone={
              row.type === "GRADE" || row.type === "ACHIEVEMENT"
                ? "brand"
                : row.type === "WARNING" || row.type === "ASSIGNMENT"
                  ? "warning"
                  : "accent"
            }
          />
        ))}
      </div>

      <NotificationTabs
        filter={unreadOnly ? "unread" : "all"}
        unreadCount={unreadCount}
        totalCount={totalCount}
      />

      {notifications.length === 0 ? (
        <EmptyState
          icon={<Bell className="size-5" />}
          title={unreadOnly ? "Tidak ada notifikasi belum dibaca" : "Belum ada notifikasi"}
          description={
            unreadOnly
              ? "Semua pemberitahuan sudah kamu baca. Kerja bagus!"
              : "Pemberitahuan tentang tugas, nilai, dan pengumuman akan muncul di sini."
          }
        />
      ) : (
        <div className="space-y-2.5">
          {notifications.map((notification) => (
            <NotificationItem key={notification.id} notification={notification} />
          ))}
        </div>
      )}

      {rollup.length > 0 ? (
        <div className="flex flex-wrap items-center gap-2 rounded-xl border border-subtle bg-surface p-4">
          <span className="text-xs font-medium text-tertiary">Ringkasan jenis:</span>
          {rollup.map((row) => (
            <Badge key={row.type} variant={NOTIFICATION_TONE[row.type]}>
              {TYPE_LABELS[row.type] ?? row.type} · {row.total}
            </Badge>
          ))}
        </div>
      ) : null}
    </div>
  );
}
