import * as React from "react";
import { MancalaGame, Pit } from "mancala.js";
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";

const BoardView: FunctionComponent<{
  game: MancalaGame;
  context: Context;
  boardId: string;
  boardViewModel: BoardViewModel;
  userKey: string;
  onPitSelect: (index: number, pit: Pit) => void;
}> = ({ game, context, boardId, boardViewModel, userKey, onPitSelect: onPitSelect }) => {
  const createPitView = (key: any, pitViewModel: PitViewModel, onClick: () => void) => {
    return <PitView key={key} pitViewModel={pitViewModel} onClick={onClick} />;
  };
  const player1Pits = game?.board.player1Pits.map((pit, index) => {
    const pitViewModel = boardViewModel.pits[pit.index];
    return createPitView(index, pitViewModel, () => {
      if (game.turnPlayerId === game.player1Id && userKey === game.player1Id)
        onPitSelect(game.board.player1Pits.indexOf(pit), pit);
    });
  });
  const player2Pits = game?.board.player2Pits.map((pit, index) => {
    const pitViewModel = boardViewModel.pits[pit.index];
    return createPitView(index, pitViewModel, () => {
      if (game.turnPlayerId === game.player2Id && userKey === game.player2Id)
        onPitSelect(game.board.player2Pits.indexOf(pit), pit);
    });
  });
  const theme = context.themeManager.theme;
  const player1BankViewModel =
    boardViewModel.pits[game.board.player1BankIndex()];
  const player2BankViewModel =
    boardViewModel.pits[game.board.player2BankIndex()];
  const isPlayer2 = userKey === game?.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;
