import React, { useContext, useCallback } from "react";
import "./Placard.css";
import { assetsPath } from "./Common";
import { GlobalContext } from "./GlobalContext";
import { SxProps, useTheme } from '@mui/material/styles';
import Box from "@mui/material/Box/Box";

type PlacardProps = {
  type?: string;
  disabled?: boolean;
  count?: number;
  buildActive?: boolean;
  setBuildActive?: (b: boolean) => void;
  className?: string;
  sx?: SxProps;
};

const Placard: React.FC<PlacardProps> = ({ type, disabled, count, buildActive, setBuildActive, className, sx }) => {
  const { lastJsonMessage, sendJsonMessage } = useContext(GlobalContext);

  const dismissClicked = () => {
    setBuildActive && setBuildActive(false);
  };

  const buildClicked = () => {
    if (!type || !type.match(/^l.*/)) {
      if (!buildActive) {
        setBuildActive && setBuildActive(true);
      }
    }
  };

  const roadClicked = () => {
    sendJsonMessage({ type: "buy-road" });
    setBuildActive && setBuildActive(false);
  };
  const settlementClicked = () => {
    sendJsonMessage({ type: "buy-settlement" });
    setBuildActive && setBuildActive(false);
  };
  const cityClicked = () => {
    sendJsonMessage({ type: "buy-city" });
    setBuildActive && setBuildActive(false);
  };
  const developmentClicked = () => {
    sendJsonMessage({ type: "buy-development" });
    setBuildActive && setBuildActive(false);
  };

  if (!type) return <></>;

  let t = type;
  if (type === "B") t = "blue";
  else if (type === "O") t = "orange";
  else if (type === "R") t = "red";
  else if (type === "W") t = "white";

  let buttons: React.ReactNode = <></>;
  if (!disabled && buildActive) {
    switch (t) {
      case "orange":
      case "red":
      case "white":
      case "blue":
        buttons = (
          <>
            <div onClick={dismissClicked} />
            <div onClick={roadClicked} />
            <div onClick={settlementClicked} />
            <div onClick={cityClicked} />
            <div onClick={developmentClicked} />
            <div onClick={dismissClicked} />
          </>
        );
        break;
      default:
        buttons = <></>;
    }
  }

  const style = { backgroundImage: `url(${assetsPath}/gfx/placard-${t}.png)` };

  if (!disabled) {
    return (
      <Box sx={{...sx, ...style}}
        className={`Placard${buildActive ? " Selected" : ""} ${className || ""}`}
        onClick={buildClicked}
        data-type={t}
      >
        {buttons}
      </Box>
    );
  }
  return (
    <Box sx={{...sx, ...style}} className={`Placard${buildActive ? " Selected" : ""} ${className || ""}`} data-type={t}>
      {count && <div className="Right">{count}</div>}
    </Box>
  );
};

export { Placard };
