import { MancalaGame } from "mancala.js";
import * as React from "react";
import { FunctionComponent } from "react";
import { Context } from "../context";
import { getColorByLuminance } from "../util/ColorUtil";

function getInfoPanelTextByGameState(params: {
  context: Context;
  game: MancalaGame;
  crashMessage: string;
  userKey: string;
  userKeyWhoLeave: string;
  searchingOpponent: boolean;
}): string {
  const {
    context,
    game,
    crashMessage,
    userKey,
    userKeyWhoLeave,
    searchingOpponent,
  } = params;
  if (searchingOpponent) {
    return context.texts.SearchingOpponent + " " + context.texts.PleaseWait;
  } else if (crashMessage) {
    return context.texts.GameCrashed + " " + crashMessage;
  } else if (userKeyWhoLeave) {
    let message = context.texts.OpponentLeavesTheGame;
    if (userKeyWhoLeave == userKey) {
      message = context.texts.YouLeftTheGame;
    }
    return message;
  } else if (game?.state == "ended") {
    const wonPlayer = game.getWonPlayerId();
    let whoWon =
      game.getWonPlayerId() === userKey
        ? context.texts.YouWon
        : context.texts.YouLost;
    if (!wonPlayer) {
      whoWon = context.texts.GameDraw;
    }
    return context.texts.GameEnded + " " + whoWon;
  } else {
    return game?.checkIsPlayerTurn(userKey)
      ? context.texts.YourTurn
      : context.texts.OpponentTurn;
  }
  return undefined;
}

const InfoPanelContainer: FunctionComponent<{
  context: Context;
  color: string;
}> = (props) => {
  return (
    <div
      style={{
        background: props.color,
        padding: "1vw 2vw",
        marginTop: "1vw",
        borderRadius: "10vw",
      }}
    >
      {props.children}
    </div>
  );
};

const InfoPanel: FunctionComponent<{
  context: Context;
  game: MancalaGame;
  crashMessage: string;
  userKey: string;
  userKeyWhoLeave: string;
  searchingOpponent: boolean;
}> = ({
  context,
  game,
  crashMessage,
  userKey,
  userKeyWhoLeave,
  searchingOpponent,
}) => {
  const isUserTurn = game?.checkIsPlayerTurn(userKey);
  const containerColor = isUserTurn
    ? context.themeManager.theme.playerTurnColor
    : context.themeManager.theme.holeColor;
  const textColor = getColorByLuminance(
    containerColor,
    context.themeManager.theme.primary,
    context.themeManager.theme.primaryLight
  );
  return (
    <InfoPanelContainer context={context} color={containerColor}>
      <h4 style={{ margin: "0", color: textColor }}>
        {getInfoPanelTextByGameState({
          context,
          game,
          crashMessage,
          userKey,
          userKeyWhoLeave,
          searchingOpponent,
        })}
      </h4>
    </InfoPanelContainer>
  );
};

export default InfoPanel;
