import * as React from "react";
import { FunctionComponent, useEffect, useState } from "react";
import BoardView from "./components/BoardView";
import { context } from "./context";
import { RTMTWS } from "./rtmt/rtmt_websocket";
import {
  channel_game_move,
  channel_leave_game,
  channel_on_game_crashed,
  channel_on_game_start,
  channel_on_game_update,
  channel_on_game_user_leave,
} from "./channel_names";
import Button from "./components/Button";
import InfoPanel from "./components/InfoPanel";
import { CommonMancalaGame, MancalaGame, Pit } from "mancala.js";
import { GameMove } from "./models/GameMove";
import PitAnimator from "./animation/PitAnimator";
import BoardViewModel from "./viewmodel/BoardViewModel";
import { v4 } from "uuid";
import { Menu, MenuButton, MenuItem } from "@szhsin/react-menu";
import "@szhsin/react-menu/dist/index.css";
import "@szhsin/react-menu/dist/transitions/slide.css";
import { getColorByLuminance } from "./util/ColorUtil";

type ConnectionState = "connecting" | "error" | "connected" | "reconnecting";

const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
  const [userKey, setUserKey] = useState(undefined);

  const [connectionState, setConnetionState] =
    useState<ConnectionState>("connecting");

  const [searchingOpponent, setSearchingOpponent] = useState<boolean>(false);

  const [game, setGame] = useState<CommonMancalaGame>(undefined);

  const [crashMessage, setCrashMessage] = useState<string>(undefined);

  const [userKeyWhoLeave, setUserKeyWhoLeave] = useState<string>(undefined);

  const [boardViewModel, setBoardViewModel] = useState<BoardViewModel>(null);

  const [boardId, setBoardId] = useState<string>();

  const [pitAnimator, setPitAnimator] = useState<PitAnimator>();

  const onConnectionDone = () => {
    setConnetionState("connected");
  };

  const onConnectionLost = () => {
    connectToServer("reconnecting");
  };

  const onConnectionError = (event: Event) => {
    setConnetionState("error");
  };

  const connectToServer = (connectionState: ConnectionState) => {
    setConnetionState(connectionState);
    context.userKeyStore.getUserKey((userKey: string) => {
      setUserKey(userKey);
      const rtmtws = context.rtmt as RTMTWS;
      if (rtmtws) {
        rtmtws.initWebSocket(
          userKey,
          onConnectionDone,
          onConnectionLost,
          onConnectionError
        );
      } else {
        console.error("context.rtmt is not RTMTWS");
      }
    });
  };

  const listenMessages = (pitAnimator: PitAnimator) => {
    context.rtmt.listenMessage(channel_on_game_start, (message: Object) => {
      const newGame: CommonMancalaGame = message as CommonMancalaGame;
      const mancalaGame = MancalaGame.createFromMancalaGame(newGame);
      setSearchingOpponent(false);
      setGame(mancalaGame);
      pitAnimator.setNewGame(mancalaGame);
    });

    context.rtmt.listenMessage(channel_on_game_update, (message: Object) => {
      const newGame: CommonMancalaGame = message as CommonMancalaGame;
      const mancalaGame = MancalaGame.createFromMancalaGame(newGame);
      setGame(mancalaGame);
      pitAnimator.setUpdatedGame(mancalaGame);
    });

    context.rtmt.listenMessage(channel_on_game_crashed, (message: any) => {
      const newCrashMessage = message as string;
      console.error("on_game_crash");
      console.error(newCrashMessage);
      setCrashMessage(newCrashMessage);
    });

    context.rtmt.listenMessage(channel_on_game_user_leave, (message: any) => {
      const userKeyWhoLeave = message;
      setUserKeyWhoLeave(userKeyWhoLeave);
    });
  };

  const updateBoardViewModel = (boardViewModel: BoardViewModel) => {
    boardViewModel.id = v4();
    setBoardId(boardViewModel.id);
    setBoardViewModel(boardViewModel);
  };

  React.useEffect(() => {
    const pitAnimator = new PitAnimator(context, updateBoardViewModel);
    setPitAnimator(pitAnimator);
    listenMessages(pitAnimator);
    connectToServer("connecting");
    return () => {
      pitAnimator.dispose();
    };
  }, []);

  React.useEffect(() => {
    context.themeManager.onThemeChange = () => {
      updateBoardViewModel(pitAnimator.getBoardViewModelFromGame(game));
    };
  }, [boardViewModel]);

  const resetGameState = () => {
    setGame(undefined);
    setCrashMessage(undefined);
    setUserKeyWhoLeave(undefined);
  };

  const newGameClick = () => {
    resetGameState();
    setSearchingOpponent(true);
    context.rtmt.sendMessage("new_game", {});
  };

  const leaveGame = () => {
    context.rtmt.sendMessage(channel_leave_game, {});
  };

  const getBoardIndex = (index: number) => {
    if (userKey === game.player2Id) return index + game.board.pits.length / 2;
    return index;
  };

  const onHoleSelect = (index: number, pit: Pit) => {
    //TODO : stoneCount comes from view model!
    if (pit.stoneCount === 0) {
      //TODO : warn user
      return;
    }
    boardViewModel.pits[getBoardIndex(index)].pitColor =
      context.themeManager.theme.pitSelectedColor;
    updateBoardViewModel(boardViewModel);
    const gameMove: GameMove = { index: index };
    context.rtmt.sendMessage(channel_game_move, gameMove);
  };

  const showConnectionState = connectionState != "connected";

  const connectionStateText = () => {
    let map: { [key: string]: string } = {
      connecting: context.texts.Connecting,
      connected: context.texts.Connected,
      error: context.texts.CannotConnect,
      reconnecting: context.texts.ConnectingAgain,
    };

    return map[connectionState];
  };

  const renderNewGameButton = () => {
    const newGame = (
      <Button
        context={context}
        text={context.texts.NewGame}
        color={context.themeManager.theme.primary}
        onClick={newGameClick}
      />
    );
    if (userKeyWhoLeave) {
      return newGame;
    }
    if (crashMessage) {
      return newGame;
    }
    if (!game) {
      return newGame;
    } else if (game.state == "ended") {
      return newGame;
    }
    return <></>;
  };
  const menuTextColor = getColorByLuminance(
    context.themeManager.theme.appBarBgColor,
    context.themeManager.theme.primary,
    context.themeManager.theme.primaryLight
  );
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        background: context.themeManager.theme.background,
        flex: "1",
      }}
    >
      {showConnectionState && (
        <div
          style={{
            position: "absolute",
            bottom: "0px",
            left: "0px",
            padding: "15px ",
            borderTopRightRadius: "1vw",
            minWidth: "10vw",
            minHeight: "1vw",
            background: context.themeManager.theme.primary,
            color: context.themeManager.theme.primaryLight,
          }}
        >
          {connectionStateText()}
        </div>
      )}
      <div
        style={{
          padding: "0px 4vw",
          background: context.themeManager.theme.appBarBgColor,
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          alignSelf: "stretch",
        }}
      >
        <h1 style={{ color: menuTextColor, margin: "10px 0px" }}>
          {context.texts.Mancala}
        </h1>
        <div
          style={{
            display: "flex",
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <div
            style={{
              marginRight: "1vw",
              display: "flex",
              alignItems: "center",
            }}
          >
            <Menu
              menuStyle={{
                background: context.themeManager.theme.appBarBgColor,
              }}
              menuButton={
                <span
                  style={{ color: menuTextColor }}
                  class="material-symbols-outlined"
                >
                  light_mode
                </span>
              }
              transition
              align="end"
            >
              {context.themeManager.themes.map((theme) => {
                return (
                  <MenuItem
                    style={{
                      color: menuTextColor,
                    }}
                    onMouseOver={(event) =>
                      (event.target.style.background =
                        context.themeManager.theme.background)
                    }
                    onMouseOut={(event) =>
                      (event.target.style.background = "transparent")
                    }
                    onClick={() => (context.themeManager.theme = theme)}
                  >
                    <div
                      style={{
                        borderRadius: "5vw",
                        background: theme.boardColor,
                        width: "1vw",
                        height: "1vw",
                        marginRight: "1vw",
                      }}
                    ></div>
                    {theme.name}
                  </MenuItem>
                );
              })}
            </Menu>
          </div>
          {renderNewGameButton()}
          {game &&
            !userKeyWhoLeave &&
            !crashMessage &&
            (game?.state === "playing" || game?.state === "initial") && (
              <Button
                context={context}
                color={context.themeManager.theme.primary}
                text={context.texts.Leave}
                onClick={leaveGame}
              />
            )}
        </div>
      </div>
      <InfoPanel
        context={context}
        game={game}
        crashMessage={crashMessage}
        userKey={userKey}
        userKeyWhoLeave={userKeyWhoLeave}
        searchingOpponent={searchingOpponent}
      />
      {game && boardViewModel && (
        <BoardView
          userKey={userKey}
          game={game}
          boardId={boardId}
          boardViewModel={boardViewModel}
          context={context}
          onHoleSelect={onHoleSelect}
        />
      )}
    </div>
  );
};

export default Home;
