import * as React from "react";
import { FunctionComponent } from "react";
import { Context } from "../../context/context";
import BoardViewModel from "../../viewmodel/BoardViewModel";
import PitViewModel from "../../viewmodel/PitViewModel";
import PitView from "./PitView";
import StoreView from "./StoreView";
import { Game } from "../../models/Game";
import { Pit } from "mancala.js";

const BoardView: FunctionComponent<{
  game: Game;
  context: Context;
  boardId: string;
  boardViewModel: BoardViewModel;
  userKey: string;
  onPitSelect: (index: number, pit: Pit) => void;
}> = ({ game, context, boardId, boardViewModel, userKey, onPitSelect: onPitSelect }) => {
  const mancalaGame = game?.mancalaGame;
  const createPitView = (key: any, pitViewModel: PitViewModel, onClick: () => void) => {
    return <PitView key={key} pitViewModel={pitViewModel} onClick={onClick} />;
  };
  const player1Pits = mancalaGame?.board.player1Pits.map((pit, index) => {
    const pitViewModel = boardViewModel.pits[pit.index];
    return createPitView(index, pitViewModel, () => {
      if (mancalaGame?.turnPlayerId === mancalaGame?.player1Id && userKey === mancalaGame?.player1Id)
        onPitSelect(mancalaGame?.board.player1Pits.indexOf(pit), pit);
    });
  });
  const player2Pits = mancalaGame?.board.player2Pits.map((pit, index) => {
    const pitViewModel = boardViewModel.pits[pit.index];
    return createPitView(index, pitViewModel, () => {
      if (mancalaGame?.turnPlayerId === mancalaGame?.player2Id && userKey === mancalaGame?.player2Id)
        onPitSelect(mancalaGame?.board.player2Pits.indexOf(pit), pit);
    });
  });
  const theme = context.themeManager.theme;
  const player1BankViewModel =
    boardViewModel.pits[mancalaGame?.board.player1BankIndex()];
  const player2BankViewModel =
    boardViewModel.pits[mancalaGame?.board.player2BankIndex()];
  const isPlayer2 = userKey === mancalaGame?.player2Id;
  return (
    <div className="board" style={{ background: theme.boardColor }}>
      <StoreView
        context={context}
        pitViewModel={isPlayer2 ? player2BankViewModel : player1BankViewModel}
        gridColumn="8 / 9"
        gridRow="1 / 3"
      />
      <StoreView
        context={context}
        pitViewModel={isPlayer2 ? player1BankViewModel : player2BankViewModel}
        gridColumn="1 / 2"
        gridRow="1 / 3"
      />
      {isPlayer2 ? player1Pits?.reverse() : player2Pits?.reverse()}
      {isPlayer2 ? player2Pits : player1Pits}
      <style jsx>{`
        .board {
          padding: 2vw;
          display: grid;
          grid-template-columns: repeat(8, 11vw);
          grid-template-rows: repeat(2, 11vw);
          border-radius: 3vw;
          transition: background-color 0.5s;
        }
      `}</style>
    </div>
  );
};

export default BoardView;
