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 {
  attachHandlerToStartRoundEvent,
  attachHandlerToUpdateLobbyEvent,
  PieceId,
} from "interface";

export interface AppProps {
  socket: Socket;
}

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

  const [initialPlayerNames, setInitialPlayerNames] = useState([] as string[]);
  const [gameCode, setGameCode] = useState("");
  const [initialPieceIds, setInitialPieceIds] = useState([] as PieceId[]);

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

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

export default App;
