import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { Bell } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useVisibilityAwareRefetchInterval } from "@/hooks/useVisibilityAwareRefetchInterval";
import { POLL_INTERVALS } from "@/shared/config/polling";
import { fetchNotificationsUnreadCount } from "@/lib/userNotificationsApi";
import { cn } from "@/lib/utils";

/**
 * Header bell: unread badge + link to `/dashboard/notifications`.
 * Works for any logged-in dashboard user; applicants get counts, staff usually zero.
 */
export function NotificationBell({ className }: { className?: string }) {
  const unreadPoll = useVisibilityAwareRefetchInterval(POLL_INTERVALS.notificationsUnreadCount);
  const { data: count = 0, isError } = useQuery({
    queryKey: ["notifications-unread-count"],
    queryFn: fetchNotificationsUnreadCount,
    refetchInterval: unreadPoll,
    refetchOnWindowFocus: true,
    staleTime: 30_000,
  });

  const showBadge = !isError && count > 0;

  return (
    <Button variant="ghost" size="icon" className={cn("relative shrink-0", className)} asChild>
      <Link to="/dashboard/notifications" aria-label="Thông báo">
        <Bell className="h-5 w-5" aria-hidden />
        {showBadge ? (
          <span
            className="absolute right-1 top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-semibold text-destructive-foreground"
            aria-hidden
          >
            {count > 99 ? "99+" : count}
          </span>
        ) : null}
      </Link>
    </Button>
  );
}
