import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import appLogo from '../../assets/images/applogo.png';
import styles from './Lobby.module.css';
import api from '../../services/api';
import { generateUniqueId } from '../../shared/utils/crypto';

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();
      navigate(`/lobby/${newSessionId}`);
    } else {
      // Fetch users in the session
      api
        .get(`/session/${sessionId}/users`)
        .then((response) => {
          setUsers(response.data);
        })
        .catch((error) => {
          console.error('Error fetching users:', error);
        });
    }
  }, [navigate, sessionId]);

  const handleJoinSession = async () => {
    const userId = generateUniqueId(); // Generate unique ID for user

    // Check if the username is already taken
    if (users.some((user) => user.username === username)) {
      setIsUsernameTaken(true);
      return;
    }

    // Add the user to the session
    try {
      await api.post(`/session/${sessionId}/user`, { userId, username });

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

      // Navigate to the session
      navigate(`/session/${sessionId}`);
    } catch (error) {
      console.error('Error joining session:', error);
    }
  };

  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(({ id, username }) => (
          <section key={id}>{username}</section>
        ))}
      </section>
    </div>
  );
};

export default Lobby;
