import { Cell, directions, Exit, PieceId } from "interface";
import "./BoardCell.scss";
import { useState } from "react";

export interface BoardCellProps {
  cell: Cell;
  dice: {
    pieceId: PieceId;
    isSelected: boolean;
    isDisabled: boolean;
    rotation: number;
  }[];
  setDice: React.Dispatch<
    React.SetStateAction<
      {
        pieceId: PieceId;
        isSelected: boolean;
        isDisabled: boolean;
        rotation: number;
      }[]
    >
  >;
  refreshBoardRender: () => void;
}

const BoardCell = (props: BoardCellProps) => {
  const { cell, dice, setDice, refreshBoardRender } = props;
  const [pieceRotationAngle, setPieceRotationAngle] = useState(0);
  const handleBoardCellClick = () => {
    const selectedDie = dice.find((die) => die.isSelected);
    if (!selectedDie) return;
    try {
      cell.placePiece(
        selectedDie.pieceId,
        selectedDie.rotation as 0 | 90 | 180 | 270,
      );
    } catch (error) {
      console.log(error);
      return;
    }
    setDice(
      dice.map((die) => {
        return die !== selectedDie
          ? die
          : {
              ...selectedDie,
              isSelected: false,
              isDisabled: true,
            };
      }),
    );
    setPieceRotationAngle(selectedDie.rotation);
    refreshBoardRender();
  };

  return (
    <div
      className={"cell " + cell.cellType.toLowerCase()}
      onClick={handleBoardCellClick}
    >
      {directions.map((direction) => {
        const traversedNode = cell.getNodeAt(direction).traverseBorder();
        const isExit = traversedNode instanceof Exit;
        if (!isExit) return;
        const className =
          `exit-${direction.toLowerCase()}` +
          ` exit-${(traversedNode as Exit).type.toLowerCase()}`;
        return (
          <div className="exit">
            <div className={className} />
          </div>
        );
      })}
      {cell.placedPiece && (
        <img
          className={`piece rotate-${pieceRotationAngle}`}
          src={`pieces/${cell.placedPiece.id}.jpeg`}
        ></img>
      )}
    </div>
  );
};

export default BoardCell;
