import React, { useCallback, useState } from "react";
import { Socket } from "socket.io-client";
import LandingPage from "./pages/landing/LandingPage";
import GamePage from "./pages/game/GamePage";
import "./App.scss";
import LobbyPage from "./pages/lobby/LobbyPage";
import { attachHandlerToUpdateLobbyEvent } from "interface";

export interface AppProps {
  socket: Socket;
}

const App = (props: AppProps) => {
  const { socket } = props;
  const [renderedPage, setRenderedPage] = useState("LANDING");

  const [initialPlayerNames, setInitialPlayerNames] = useState([""]);
  const [gameCode, setGameCode] = useState("");

  const setupNextPageTransition = useCallback(() => {
    if (renderedPage === "LANDING") {
      attachHandlerToUpdateLobbyEvent(socket, (event) => {
        setInitialPlayerNames(event.playerNames);
        setGameCode(event.gameCode);
        setRenderedPage("LOBBY");
      });
    }
  }, [renderedPage]);

  setupNextPageTransition();

  return (
    <div className="app">
      {renderedPage === "LANDING" && <LandingPage {...props} />}
      {renderedPage === "LOBBY" && (
        <LobbyPage
          {...props}
          initialPlayerNames={initialPlayerNames}
          gameCode={gameCode}
        />
      )}
      {renderedPage === "GAME" && <GamePage />}
    </div>
  );
};

export default App;
