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

export interface ActiveUser {
    id: string;
    name: string;
    email: string;
    logtoId: string;
    lastSeenAt: string;
}

export const usePresence = () => {
    const { isSignedIn, appUser, isLoading } = useAuth();
    const [activeUsers, setActiveUsers] = useState<ActiveUser[]>([]);

    const sendHeartbeat = useCallback(async () => {
        // Only send heartbeat if user is signed in, not loading, and appUser exists
        if (!isSignedIn || isLoading || !appUser) return;

        try {
            await api.post('/users/heartbeat');
        } catch (error) {
            console.error('Failed to send heartbeat', error);
        }
    }, [isSignedIn, isLoading, appUser]);

    const fetchActiveUsers = useCallback(async () => {
        // Only fetch if user is signed in, not loading, and appUser exists
        if (!isSignedIn || isLoading || !appUser) return;

        try {
            const response = await api.get<ActiveUser[]>('/users/active');
            setActiveUsers(response.data);
        } catch (error) {
            console.error('Failed to fetch active users', error);
        }
    }, [isSignedIn, isLoading, appUser]);

    useEffect(() => {
        // Wait until user is signed in, not loading, and appUser exists
        if (!isSignedIn || isLoading || !appUser) return;

        // Initial call
        sendHeartbeat();
        fetchActiveUsers();

        // Interval
        const interval = setInterval(() => {
            sendHeartbeat();
            fetchActiveUsers();
        }, 60000); // 1 minute

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

    return { activeUsers };
};
