"use client";

import { useState, useEffect, useRef } from "react";
import { useAuth } from "@/lib/AuthContext";
import { Bell } from "lucide-react";
import NotificationPanel from "./NotificationPanel";

export default function NotificationBell() {
  const { user, token } = useAuth();
  const [unreadCount, setUnreadCount] = useState(0);
  const [panelOpen, setPanelOpen] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);

  const fetchUnreadCount = async () => {
    if (!token) return;
    try {
      const res = await fetch("/mobile/api/notifications/unread-count", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setUnreadCount(data.count);
      }
    } catch {
      // ignore
    }
  };

  useEffect(() => {
    fetchUnreadCount();
    // Poll every 30 seconds
    const interval = setInterval(fetchUnreadCount, 30000);
    return () => clearInterval(interval);
  }, [token]);

  // Close panel on outside click
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        setPanelOpen(false);
      }
    };
    if (panelOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [panelOpen]);

  if (!user) return null;

  return (
    <div ref={panelRef} className="relative">
      <button
        onClick={() => setPanelOpen(!panelOpen)}
        className="relative p-2 rounded-full hover:bg-gray-800/60 transition-colors"
        aria-label="Notifications"
      >
        <Bell size={20} className="text-gray-300" />
        {unreadCount > 0 && (
          <span className="absolute -top-0.5 -right-0.5 flex items-center justify-center w-4.5 h-4.5 text-[10px] font-bold bg-red-500 text-white rounded-full min-w-[18px] min-h-[18px] leading-none">
            {unreadCount > 99 ? "99+" : unreadCount}
          </span>
        )}
      </button>

      {panelOpen && (
        <NotificationPanel
          token={token}
          onClose={() => setPanelOpen(false)}
          onCountChange={setUnreadCount}
        />
      )}
    </div>
  );
}
