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 LobbyPage from "./pages/lobby/LobbyPage";
import {
  attachHandlerToStartRoundEvent,
  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");
      });
    } else if (renderedPage === "LOBBY") {
      attachHandlerToStartRoundEvent(socket, (event) => {
        setRenderedPage("GAME");
      });
    }
  }, [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;
