import ms from "pretty-ms";
import iso from "iso-3166-1";
import { useState } from "react";
import { useGameId } from "../../../domain/gameStore";
import { useGameConfig, usePlayers } from "../../../hooks/useGameInfo";
import ClickToCopy from "../../util/ClickToCopy";
import Loading from "../../util/Loading";
import JoinForm from "./JoinForm";
import styles from "./Lobby.module.css";
import StartGame from "./StartGame";
import {
  NORMAL,
  TIME_BANK,
  FROZEN,
  COUNTRY_RACE,
} from "../../../domain/ruleSets";

export const GameInfo = () => {
  const { rounds, timer, countryLock, ruleSet } = useGameConfig();

  if (!rounds || !timer) {
    return <Loading />;
  }

  let explanation;
  switch (ruleSet) {
    case COUNTRY_RACE:
      explanation = `${rounds !== 1 ? ", each" : ""} with a ${ms(
        timer * 1000
      )} time limit, where you must be the fastest to select the right country`;
      break;
    case FROZEN:
      explanation = `${rounds !== 1 ? ", each" : ""} with a ${ms(
        timer * 1000
      )} time limit, and you will not be able to adjust your view`;
      break;
    case TIME_BANK:
      explanation = `with a ${ms(
        timer * 1000 * rounds
      )} time bank across all rounds`;
      break;
    case NORMAL: // fall-through
    default:
      explanation = `${rounds !== 1 ? ", each" : ""} with a ${ms(
        timer * 1000
      )} time limit`;
      break;
  }

  return (
    <>
      <span className={styles.label}>
        Game will run for {rounds} round{rounds !== 1 && "s"}
        {explanation}
      </span>
      {countryLock && (
        <span className={styles.label}>
          This game will only use locations within:{" "}
          {iso.whereAlpha2(countryLock).country}
        </span>
      )}
    </>
  );
};

const getUrl = gameId => {
  const u = new URL(window.location.href);
  u.searchParams.append("join", gameId);
  return u.href;
};

export const PlayerList = ({ playerNames }) => (
  <div className={styles.players}>
    <span className={styles.playersTitle}>Players</span>
    <ul>
      {playerNames.map(name => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  </div>
);

const Lobby = ({ onStart }) => {
  const gameId = useGameId();
  const players = usePlayers();
  const [joined, setJoined] = useState(false);

  if (!players) {
    return <Loading />;
  }

  return (
    <div className={styles.page}>
      <div className={styles.info}>
        <GameInfo />
        <div className={styles.form}>
          {joined ? (
            <StartGame onStart={onStart} />
          ) : (
            <JoinForm onJoined={() => setJoined(true)} />
          )}
        </div>
        <span className={styles.label}>
          <ClickToCopy text={getUrl(gameId)}>
            Click here to copy an invite link!
          </ClickToCopy>
        </span>
      </div>
      <PlayerList playerNames={players.map(({ name }) => name)} />
    </div>
  );
};

export default Lobby;
