import React, { useState } from "react";
import Loading from "../loading.component";
import { createGame, joinGame } from "../../services/ggsh.service";

// TODO set round timer for new game

const initialState = playerName => ({
  loading: false,
  gameId: null,
  playerName,
});

const PlayerName = ({ playerName, onChangePlayerName }) => (
  <div style={{
    display: "flex",
    flexFlow: "column nowrap",
    justifyContent: "center",
    alignItems: "center",
  }}>
    <span style={{ padding: "0.2em" }}>Player Name</span>
    <input style={{ padding: "0.1em" }} type="text" value={playerName} onChange={onChangePlayerName} />
  </div>
);

const NewGame = ({ onCreateGame, cannotCreateGame }) => (
  <button onClick={onCreateGame} disabled={cannotCreateGame}>
    Create New Game
  </button>
);

const JoinGame = ({ gameId, onChangeGameId, onJoinGame, cannotJoinGame }) => (
  <div style={{
    display: "flex",
    flexFlow: "column nowrap",
    justifyContent: "center",
    alignItems: "center",
  }}>
    <span style={{ padding: "0.1em" }}>Game ID:</span>
    <input style={{ margin: "0.1em" }} type="text" value={gameId} onChange={onChangeGameId} />
    <button style={{ margin: "0.1em" }} onClick={onJoinGame} disabled={cannotJoinGame}>
      Join Existing Game
    </button>
  </div>
);

const PreGame = ({ initPlayerName, onGameJoined }) => {
  const [state, setState] = useState(initialState(initPlayerName));
  const { loading, gameId, playerName } = state;

  if (loading) {
    return <Loading/>
  }

  const onChangePlayerName = ({ target }) => setState({ ...state, playerName: target.value.trim() });
  const onChangeGameId = ({ target }) => setState({ ...state, gameId: target.value.trim() });
  const onCreateGame = async () => {
    setState({ ...state, loading: true })
    const gameId = await createGame(playerName, 300);
    onGameJoined({ gameId, playerName });
  };
  const cannotCreateGame = !playerName || playerName.length === 0;
  const onJoinGame = async () => {
    // TODO would like to support re-joining a game you left
    setState({ ...state, loading: true })
    await joinGame(gameId, playerName);
    onGameJoined({ gameId, playerName });
  };
  const cannotJoinGame = cannotCreateGame || !gameId || gameId.length === 0;

  return (
    <div>
      <PlayerName {...{ playerName, onChangePlayerName }} />
      <hr/>
      <NewGame {...{ onCreateGame, cannotCreateGame }} />
      <hr/>
      <JoinGame {...{ gameId, onChangeGameId, onJoinGame, cannotJoinGame }} />
    </div>
  );
}

export default PreGame;
