import React, { useState, useEffect } from 'react';
import { ref, onValue, set } from 'firebase/database';
import { realtimeDb } from '../../services/firebase';
import { generateUniqueId } from '../../utils/crypto';
import appLogo from '../../assets/images/applogo.png';
import styles from './Lobby.module.css';
import { useNavigate, useParams } from 'react-router-dom';
import { auth } from '../../services/firebase';

const Lobby = ({ onJoinSession = () => {} }) => {
  const navigate = useNavigate();
  const [username, setUsername] = useState('');
  const [users, setUsers] = useState([]);
  const [isUsernameTaken, setIsUsernameTaken] = useState(false);
  const { sessionId } = useParams();

  useEffect(() => {
    // Get or generate the session ID
    if (!sessionId) {
      const newSessionId = generateUniqueId();
      // Update the URL with the session ID if it wasn't already there
      navigate(`/lobby/${newSessionId}`);
    }

    const sessionRef = ref(realtimeDb, `sessions/${sessionId}/users`);

    // Listen for changes to the session users data
    const unsubscribe = onValue(sessionRef, (snapshot) => {
      const users = snapshot.val();
      if (!users) return;

      const userList = Object.entries(users).map(([uid, userInfo]) => ({
        uid,
        username: userInfo.username,
      }));
      setUsers(userList);
    });

    return () => {
      unsubscribe();
    };
  }, [navigate, sessionId]);

  const handleJoinSession = async () => {
    const user = auth.currentUser;
    const userId = user ? user.uid : generateUniqueId();

    // Check if the uid is already part of the session
    if (users.includes(userId)) {
      setIsUsernameTaken(true);
      return;
    } else {
      // Set the initial vote for the user
      const voteRef = ref(realtimeDb, `sessions/${sessionId}/votes/${userId}`);
      await set(voteRef, -1);

      // Add the user to the session's user list with their uid and username
      const userRef = ref(realtimeDb, `sessions/${sessionId}/users/${userId}`);
      await set(userRef, {
        username: username,
        uid: userId,
      });

      // Also save the current session ID under the user's record in the database
      const userSessionRef = ref(realtimeDb, `users/${userId}`);
      await set(userSessionRef, {
        currentSessionId: `session/${sessionId}`,
      });

      // Call the onJoinSession callback with the username
      onJoinSession(userId);

      // Navigate to the session
      navigate(`/session/${sessionId}`);
    }
  };

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      handleJoinSession();
    }
  };

  return (
    <div className={styles.lobby}>
      <img className={styles.appLogo} src={appLogo} alt="logo" />
      <h2>Enter Your Username</h2>
      <div className={styles.form}>
        <input
          type="text"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          maxLength={24}
          onKeyDown={handleKeyDown}
        />
        <div className={styles.button} onClick={handleJoinSession}>
          Join Session
        </div>
      </div>
      {isUsernameTaken && (
        <p>Username is already taken. Please choose another.</p>
      )}
      <br />
      <h3>Current Users In Session</h3>
      <section className={styles.list}>
        {users.map(({ uid, username }) => (
          <section key={uid}>{username}</section>
        ))}
      </section>
    </div>
  );
};

export default Lobby;
