import { useEffect, useState } from 'react';
import { ref, onValue, remove } from 'firebase/database';
import { realtimeDb } from '../../services/firebase';
import { useNavigate } from 'react-router-dom';
import { generateUniqueId } from '../../utils/crypto';
import { auth } from '../../services/firebase';

const UserSessionListener = () => {
  const navigate = useNavigate();
  const user = auth.currentUser;
  const userId = user ? user.uid : generateUniqueId();
  const [isRedirecting, setIsRedirecting] = useState(false);

  useEffect(() => {
    const userRef = ref(realtimeDb, `users/${userId}/currentSessionId`);

    const unsubscribe = onValue(userRef, async (snapshot) => {
      const currentSessionId = snapshot.val() || generateUniqueId();

      // Only redirect if the user is not already being redirected
      if (
        !isRedirecting &&
        currentSessionId &&
        currentSessionId.startsWith('lobby')
      ) {
        setIsRedirecting(true);

        console.log(`Removing user from: users/${userId}`);

        // Remove the entire user entry from the database
        const fullUserRef = ref(realtimeDb, `users/${userId}`);
        await remove(fullUserRef);

        navigate(`/${currentSessionId}`);

        setIsRedirecting(false);
      }
    });

    return () => unsubscribe();
  }, [userId, navigate, isRedirecting]);

  return null;
};

export default UserSessionListener;
