import { PieceId } from "interface";
import "./DiceSet.scss";
import Die from "./Die";
import React from "react";

export interface DiceSetProps {
  dice: {
    pieceId: PieceId;
    isSelected: boolean;
    isDisabled: boolean;
    rotation: number;
  }[];
  setDice: React.Dispatch<
    React.SetStateAction<
      {
        pieceId: PieceId;
        isSelected: boolean;
        isDisabled: boolean;
        rotation: number;
      }[]
    >
  >;
}
const DiceSet = (props: DiceSetProps) => {
  const { dice, setDice } = props;
  const handleDieClick = (die: {
    pieceId: PieceId;
    isSelected: boolean;
    isDisabled: boolean;
    rotation: number;
  }) => {
    if (die.isDisabled) return;
    const newDiceState = dice.map((oldDie) => {
      const isSelected = die === oldDie;
      return {
        ...oldDie,
        isSelected: isSelected,
      };
    });
    setDice(newDiceState);
  };

  const handleRotateButton = (rotation: number) => {
    const newDiceState = dice.map((die) => {
      if (!die.isSelected) return die;
      const rotationAngle = (die.rotation + rotation + 360) % 360;
      return {
        ...die,
        rotation: rotationAngle,
      };
    });
    setDice(newDiceState);
  };

  return (
    <React.Fragment>
      <div className="dice-set-actions">
        <img
          src="./rotate-icon.png"
          onClick={() => handleRotateButton(-90)}
        ></img>
        <img
          src="./rotate-icon.png"
          className="icon-inverted"
          onClick={() => handleRotateButton(90)}
        ></img>
      </div>
      <div className="dice-set">
        {dice.map((die) => (
          <Die die={die} handleDieClick={handleDieClick} />
        ))}
      </div>
    </React.Fragment>
  );
};

export default DiceSet;
