import { useEffect, useState } from 'react';
import './App.css';
import { setupSocketEffect, socket } from './socket';
import RoomSelection from './components/RoomSelection';
import Game from './components/Game';

const App = () => {
  const [room, setRoom] = useState({});

  useEffect(() => {
    console.log("Attempting to connect socket");
    socket.connect();

    const cleanup = setupSocketEffect(socket, (room) => {
      console.log("Room state updated", room);
      setRoom(room);
    });

    return () => {
      cleanup();
      socket.disconnect();
    };
  }, []);

  useEffect(() => setupSocketEffect(socket, setRoom), []);

  const handleDisconnect = () => {
    console.log('Disconnecting');
    socket.disconnect();
  }

  const handleJoinRoom = (username, room) => {
    console.log('Joining room', room);
    socket.connect();
    socket.emit('joinRoom', { username, room });
  }

  const handleCreateRoom = (username, rows, cols, bombs, autoflag, gameMode) => {
    console.log('Creating room', { username, rows, cols, bombs, autoflag, gameMode });
    socket.connect();
    socket.emit('createRoom', { username, rows, cols, bombs, autoflag, gameMode });
    console.log(socket);
  };

  const handleTileClick = (tileId) => {
    socket.emit('tileClick', { tileId });
  }

  const handleSelectionConfirm = (tileId) => {
    socket.emit('tileSelect', { tileId });
  }

  const handleTileFlag = (tileId) => {
    socket.emit('tileFlag', { tileId });
  }

  return (
    <>
      {
        room && room.id
          ? <Game
              room={room}
              playerSocketId={socket.id}
              handleDisconnect={handleDisconnect}
              handleTileClick={handleTileClick}
              handleSelectionConfirm={handleSelectionConfirm}
              handleTileFlag={handleTileFlag}
            />
          : <RoomSelection handleJoinRoom={handleJoinRoom} handleCreateRoom={handleCreateRoom} />
      }
    </>
  );
}

export default App
