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

export interface BoardCellProps {
  cell: Cell;
  refreshBoardRender: () => void;
  modifyDieState: (
    matcher: (die: DieViewProps) => boolean,
    newStateComputer: (die: DieViewProps) => Partial<DieViewProps>,
  ) => void;
  fetchDie: (
    matcher: (die: DieViewProps) => boolean,
  ) => DieViewProps | undefined;
  setSpecialDieUsedInRound: React.Dispatch<React.SetStateAction<boolean>>;
  placePieceActionHandler: (pieceId: PieceId, rotation: number) => void;
}

const BoardCell = (props: BoardCellProps) => {
  const {
    cell,
    refreshBoardRender,
    modifyDieState,
    fetchDie,
    setSpecialDieUsedInRound,
    placePieceActionHandler,
  } = props;
  const [pieceRotationAngle, setPieceRotationAngle] = useState(0);
  const handleBoardCellClick = () => {
    const selectedDie = fetchDie((die) => die.isSelected);
    if (!selectedDie) return;
    try {
      placePieceActionHandler(selectedDie.pieceId, selectedDie.rotation);
    } catch (error) {
      console.log(error);
      return;
    }
    modifyDieState(
      (die) => die === selectedDie,
      () => {
        return {
          isSelected: false,
          isDisabled: true,
        };
      },
    );
    if (selectedDie.isSpecial) setSpecialDieUsedInRound(true);
    // Set rotation to the piece in the board, not the die
    setPieceRotationAngle(selectedDie.rotation);
    refreshBoardRender();
  };

  return (
    <div className={"cell"} 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>
      )}
      {cell.cellType !== CellType.NORMAL && (
        <img
          className="cell-type-icon"
          src={`./${cell.cellType.toLowerCase()}-icon.png`}
        ></img>
      )}
    </div>
  );
};

export default BoardCell;
