"use client";

import Link from "next/link";
import {
  useNotifications,
  useMarkAllNotificationsRead,
} from "@/lib/queries/use-notifications";
import { NotificationRow } from "./notification-row";

export function NotificationDropdown({
  onClose,
  seeAllHref = "/notifications",
}: {
  onClose: () => void;
  seeAllHref?: string;
}) {
  const { data, isLoading } = useNotifications("all");
  const markAll = useMarkAllNotificationsRead();

  const first = data?.pages[0];
  const items = (first?.data ?? []).slice(0, 10);

  return (
    <div
      role="menu"
      className="absolute right-0 top-full mt-2 w-80 rounded-md border border-forest/20 bg-bone shadow-lg z-50"
    >
      <div className="flex items-center justify-between px-4 py-2 border-b border-forest/10">
        <span className="text-sm font-semibold text-forest">Notifications</span>
        <button
          type="button"
          onClick={() => markAll.mutate()}
          className="text-xs text-terracotta hover:underline"
        >
          Mark all read
        </button>
      </div>

      <div className="max-h-96 overflow-y-auto">
        {isLoading ? (
          <div className="p-6 text-sm text-forest/60 text-center">Loading…</div>
        ) : items.length === 0 ? (
          <div className="p-6 text-sm text-forest/60 text-center">No notifications yet.</div>
        ) : (
          items.map((item) => <NotificationRow key={item.id} item={item} />)
        )}
      </div>

      <Link
        href={seeAllHref}
        onClick={onClose}
        className="block px-4 py-2 text-center text-xs font-medium text-forest hover:bg-bone/60 border-t border-forest/10"
      >
        See all
      </Link>
    </div>
  );
}
