import React, { useState, useEffect, useContext, useRef, useMemo } from "react";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import equal from "fast-deep-equal";

import { Dice } from "./Dice";
import { PlayerColor } from "./PlayerColor";

import "./GameOrder.css";

import { GlobalContext } from "./GlobalContext";

/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */

interface PlayerItem {
  name: string;
  color: string;
  order: number;
  orderRoll: number;
  orderStatus: string;
}

const GameOrder: React.FC = () => {
  const { lastJsonMessage, sendJsonMessage } = useContext(GlobalContext);
  const [players, setPlayers] = useState<{ [key: string]: any }>({});
  const [color, setColor] = useState<string | undefined>(undefined);
  const fields = useMemo(() => ["players", "color"], []);

  useEffect(() => {
    const data = lastJsonMessage;
    switch (data.type) {
      case "game-update":
        console.log(`GameOrder game-update: `, data.update);
        if ("players" in data.update && !equal(players, data.update.players)) {
          setPlayers(data.update.players);
        }
        if ("color" in data.update && data.update.color !== color) {
          setColor(data.update.color);
        }
        break;
      default:
        break;
    }
  }, [lastJsonMessage, players, color]);
  useEffect(() => {
    if (!sendJsonMessage) {
      return;
    }
    sendJsonMessage({
      type: "get",
      fields,
    });
  }, [sendJsonMessage, fields]);

  const rollClick = () => {
    sendJsonMessage({ type: "roll" });
  };

  let hasRolled = true;
  const playerElements: PlayerItem[] = [];
  for (const key in players) {
    const item = players[key],
      name = item.name;
    if (!name) {
      continue;
    }
    if (!item.orderRoll) {
      item.orderRoll = 0;
    }
    if (key === color) {
      hasRolled = item.orderRoll !== 0;
    }
    playerElements.push({ name, color: key, ...item });
  }

  playerElements.sort((A, B) => {
    if (A.order === B.order) {
      if (A.orderRoll === B.orderRoll) {
        return A.name.localeCompare(B.name);
      }
      return B.orderRoll - A.orderRoll;
    }
    return B.order - A.order;
  });

  const playerJSX = playerElements.map((item) => (
    <div className="GameOrderPlayer" key={`player-${item.color}`}>
      <PlayerColor color={item.color} />
      <div>{item.name}</div>
      {item.orderRoll !== 0 && (
        <>
          rolled <Dice pips={item.orderRoll} />. {item.orderStatus}
        </>
      )}
      {item.orderRoll === 0 && <>has not rolled yet. {item.orderStatus}</>}
    </div>
  ));

  return (
    <div className="GameOrder">
      <Paper>
        <div className="Title">Game Order</div>
        <div className="PlayerList">{playerJSX}</div>
        <Button disabled={hasRolled} onClick={rollClick}>
          Roll Dice
        </Button>
      </Paper>
    </div>
  );
};

export { GameOrder };
