import {
  attachHandlerToCreateLobbyError,
  CreateLobbyEvent,
  ErrorCode,
  handleCreateLobby,
  handleJoinLobby,
  JoinLobbyEvent,
} from "interface";
import React, { ChangeEvent, useState } from "react";
import { Socket } from "socket.io-client";
import "./LandingPage.scss";

export interface LandingPageProps {
  socket: Socket;
}

const LandingPage = (props: LandingPageProps) => {
  const { socket } = props;

  const createLobbyPayload: CreateLobbyEvent = { userName: "" };
  const joinLobbyPayload: JoinLobbyEvent = { userName: "", lobbyId: "" };
  const registerUsername = (event: ChangeEvent<HTMLInputElement>) => {
    createLobbyPayload.userName = event.target.value;
    joinLobbyPayload.userName = event.target.value;
  };
  const registerLobbyId = (event: ChangeEvent<HTMLInputElement>) =>
    (joinLobbyPayload.lobbyId = event.target.value);

  const [receivedError, setReceivedError] = useState("" as ErrorCode);
  const userNameErrorCodesToMessageMap = new Map([
    [ErrorCode.MISSING_USER_NAME, "Introduce your player name"],
    [
      ErrorCode.INVALID_USER_NAME,
      "Player name must be letters or spaces only and up to 25 characters",
    ],
  ]);
  const userNameErrorMessage =
    userNameErrorCodesToMessageMap.get(receivedError);

  attachHandlerToCreateLobbyError(socket, (event) =>
    setReceivedError(event.error),
  );

  return (
    <div className="landing-page">
      <div>
        <h1>Trains And Roads</h1>
      </div>
      <div className="landing-page-body">
        <div>
          <input
            placeholder="Enter username"
            onChange={registerUsername}
            maxLength={20}
          ></input>
          {userNameErrorMessage && (
            <small id="error-message">{userNameErrorMessage}</small>
          )}
          <button onClick={() => handleCreateLobby(socket, createLobbyPayload)}>
            Create Lobby
          </button>
        </div>
        <div>
          <input
            placeholder="Enter Lobby Id"
            onChange={registerLobbyId}
            maxLength={5}
          ></input>
          <button
            className="secondary"
            onClick={() => handleJoinLobby(socket, joinLobbyPayload)}
          >
            Join Lobby
          </button>
        </div>
      </div>
    </div>
  );
};
export default LandingPage;
