"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Bell } from "lucide-react";
import { Button } from "@/components/ui/button";
import { notificationsService } from "@/core/api/services/notifications";

const NOTIFICATION_COUNT_EVENT = "admin-notification-count-change";

export function notifyAdminNotificationCountChanged(unreadCount?: number) {
  if (typeof window === "undefined") return;
  window.dispatchEvent(
    new CustomEvent<number | undefined>(NOTIFICATION_COUNT_EVENT, {
      detail: unreadCount,
    })
  );
}

export function AdminNotificationBell() {
  const [unreadCount, setUnreadCount] = useState(0);

  const refreshCount = useCallback(async () => {
    try {
      const paginator = await notificationsService.list({ status: "new" });
      setUnreadCount(paginator.total ?? paginator.data.length);
    } catch {
      setUnreadCount(0);
    }
  }, []);

  useEffect(() => {
    refreshCount();

    const refreshOnFocus = () => refreshCount();
    const handleCountChange = (event: Event) => {
      const detail =
        event instanceof CustomEvent && typeof event.detail === "number"
          ? event.detail
          : null;

      if (detail !== null) {
        setUnreadCount(detail);
        return;
      }

      refreshCount();
    };

    window.addEventListener("focus", refreshOnFocus);
    window.addEventListener(NOTIFICATION_COUNT_EVENT, handleCountChange);

    const intervalId = window.setInterval(refreshCount, 30000);

    return () => {
      window.removeEventListener("focus", refreshOnFocus);
      window.removeEventListener(NOTIFICATION_COUNT_EVENT, handleCountChange);
      window.clearInterval(intervalId);
    };
  }, [refreshCount]);

  const label = unreadCount > 99 ? "99+" : String(unreadCount);

  return (
    <Link href="/admin/notification">
      <Button
        variant="ghost"
        size="icon"
        className="relative rounded-xl hover:bg-muted"
        aria-label="View notifications"
      >
        <Bell className="h-5 w-5 text-muted-foreground" aria-hidden="true" />
        {unreadCount > 0 && (
          <span className="absolute -right-0.5 -top-0.5 flex h-5 min-w-5 items-center justify-center">
            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-destructive/50 opacity-75" />
            <span className="relative inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold leading-none text-destructive-foreground">
              {label}
            </span>
          </span>
        )}
      </Button>
    </Link>
  );
}
