'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';

interface NotificationBellProps {
  onNotificationClick: () => void;
}

export default function NotificationBell({ onNotificationClick }: NotificationBellProps) {
  const { data: session } = useSession();
  const [unreadCount, setUnreadCount] = useState(0);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (session?.user?.email) {
      fetchUnreadCount();
      
      // Poll for updates every 30 seconds
      const interval = setInterval(fetchUnreadCount, 30000);
      return () => clearInterval(interval);
    }
  }, [session]);

  const fetchUnreadCount = async () => {
    try {
      setLoading(true);
      console.log('[NotificationBell] Fetching unread count...');
      
      const response = await fetch('/api/notifications/unread-count', {
        headers: {
          'x-toast-controlled': 'true' // Suppress global toast from ClientToasterBridge
        }
      });
      
      console.log('[NotificationBell] Response status:', response.status);
      
      if (response.ok) {
        const data = await response.json();
        console.log('[NotificationBell] Response data:', data);
        if (data.success && data.data) {
          setUnreadCount(data.data.unreadCount);
        } else {
          console.warn('[NotificationBell] Unexpected response format:', data);
        }
      } else {
        const errorData = await response.json().catch(() => ({}));
        console.error('[NotificationBell] API error:', response.status, errorData);
      }
    } catch (error) {
      console.error('[NotificationBell] Fetch error:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!session?.user) {
    return null;
  }

  return (
    <div className="position-relative">
      <button
        className="btn btn-link p-2 position-relative dropdown-toggle"
        onClick={onNotificationClick}
        disabled={loading}
        title="Notifications"
      >
        <img 
          src="/assets/image/notification.svg" 
          alt="Notifications" 
          width="24" 
          height="24"
        />
        {unreadCount > 0 && (
          <span className="position-absolute start-100 translate-middle badge rounded-pill bg-danger notification-badge">
            {unreadCount > 99 ? '99+' : unreadCount}
            <span className="visually-hidden">unread notifications</span>
          </span>
        )}
      </button>
    </div>
  );
}