import { useState, useEffect } from 'react';
import api from '../services/api';
import { useAuth } from '../context/useAuth';

export const useUnreadMessages = () => {
    const { isSignedIn, appUser } = useAuth();
    const [unreadCount, setUnreadCount] = useState(0);
    const [hasUnread, setHasUnread] = useState(false);

    useEffect(() => {
        if (!isSignedIn || !appUser) return;

        const fetchUnreadCount = async () => {
            try {
                const response = await api.get('/messages/unread');
                const count = response.data.length;
                setUnreadCount(count);
                setHasUnread(count > 0);
            } catch (error) {
                console.error('Error fetching unread messages:', error);
            }
        };

        // Initial fetch
        fetchUnreadCount();

        // Poll every 30 seconds
        const interval = setInterval(fetchUnreadCount, 30000);

        return () => clearInterval(interval);
    }, [isSignedIn, appUser]);

    const refreshUnreadCount = async () => {
        try {
            const response = await api.get('/messages/unread');
            const count = response.data.length;
            setUnreadCount(count);
            setHasUnread(count > 0);
        } catch (error) {
            console.error('Error fetching unread messages:', error);
        }
    };

    return { unreadCount, hasUnread, refreshUnreadCount };
};
