import { useState } from "react";
import { dispatch, usePlayerName } from "../../../domain/gameStore";
import styles from "./Lobby.module.css";

const JoinForm = ({ onJoined }) => {
  const playerName = usePlayerName();
  const [loading, setLoading] = useState(false);
  const [failed, setFailed] = useState(false);

  const onJoinGame = async () => {
    setFailed(false);
    setLoading(true);
    try {
      await dispatch.joinGame();
    } catch (err) {
      // failed to join the game
      setFailed(true);
      setLoading(false);
      return;
    }
    onJoined();
  };
  const cannotJoinGame = loading || !playerName || playerName.length === 0;

  return (
    <>
      <div className={styles.join}>
        <span className={styles.label}>Enter your name to join:</span>
        <input
          className={styles.name}
          type="text"
          value={playerName || ""}
          onChange={({ target }) => dispatch.setPlayerName(target.value)}
          onKeyDown={({ key }) => {
            if (key === "Enter") {
              onJoinGame();
            }
          }}
        />
        <button onClick={onJoinGame} disabled={cannotJoinGame} type="button">
          Join Game
        </button>
      </div>
      <div className={styles.error}>
        {failed ? "Failed to join the game! Maybe try a different name?" : ""}
      </div>
    </>
  );
};

export default JoinForm;
