import Link from "next/link";
import { requireSession } from "@/lib/auth";
import { GROUP_LABEL, getNotifications, type NotificationGroup } from "@/lib/notifications";
import { formatDateTime } from "@/lib/format";
import { PageHeader, EmptyState, Badge } from "@/components/ui";
import { MarkSeen } from "./mark-seen";

export const dynamic = "force-dynamic";

const ORDER: NotificationGroup[] = ["PERSONAL", "COMPANY", "TERRITORY", "DEPARTMENT", "TEAM"];

export default async function NotificationsPage({ searchParams }: { searchParams: Promise<{ nhom?: string }> }) {
  const session = await requireSession();
  const { nhom } = await searchParams;
  const all = await getNotifications(session);

  const active = ORDER.includes(nhom as NotificationGroup) ? (nhom as NotificationGroup) : null;
  const shown = active ? all.filter((item) => item.group === active) : all;
  const countOf = (group: NotificationGroup) => all.filter((item) => item.group === group).length;

  return (
    <>
      <MarkSeen hasNew={all.some((item) => item.unread && !item.needsAction)} />
      <PageHeader
        title="Thông báo"
        subtitle="Mọi thông tin mới liên quan tới bạn: tin của công ty, khu vực, phòng ban và việc cần bạn xử lý."
      />

      <div className="mb-4 flex w-fit flex-wrap gap-1 rounded-lg border border-[var(--color-line)] bg-white p-1">
        <Link
          href="/thong-bao"
          className={`rounded-md px-3 py-1.5 text-sm font-semibold ${!active ? "bg-brand-500 text-white" : "text-ink-500 hover:bg-ink-50"}`}
        >
          Tất cả ({all.length})
        </Link>
        {ORDER.map((group) => (
          <Link
            key={group}
            href={`/thong-bao?nhom=${group}`}
            className={`rounded-md px-3 py-1.5 text-sm font-semibold ${active === group ? "bg-brand-500 text-white" : "text-ink-500 hover:bg-ink-50"}`}
          >
            {GROUP_LABEL[group]} ({countOf(group)})
          </Link>
        ))}
      </div>

      {shown.length === 0 ? (
        <EmptyState message="Chưa có thông báo nào." hint="Khi có tin mới hoặc việc cần bạn xử lý, chúng sẽ hiện ở đây." />
      ) : (
        <div className="flex flex-col gap-2">
          {shown.map((item) => (
            <Link
              key={item.id}
              href={item.href}
              className={`card block p-3.5 hover:border-brand-300 ${item.unread ? "border-l-4 border-l-brand-500" : ""}`}
            >
              <div className="flex flex-wrap items-center gap-2">
                <span className="text-sm font-semibold text-ink-700">{item.title}</span>
                <Badge tone={item.group === "PERSONAL" ? "gold" : item.group === "COMPANY" ? "brand" : "neutral"}>
                  {GROUP_LABEL[item.group]}
                </Badge>
                {item.needsAction && <Badge tone="red">Cần xử lý</Badge>}
                {item.unread && !item.needsAction && <Badge tone="green">Mới</Badge>}
              </div>
              {item.text && <div className="mt-1 whitespace-pre-line text-xs text-ink-500">{item.text}</div>}
              <div className="mt-1 text-[11px] text-ink-400">{formatDateTime(item.at)}</div>
            </Link>
          ))}
        </div>
      )}
    </>
  );
}
