import React, { useContext, useCallback } from "react";
import "./Placard.css";
import { assetsPath } from "./Common";
import { GlobalContext } from "./GlobalContext";

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

const Placard: React.FC<PlacardProps> = ({ type, disabled, count, buildActive, setBuildActive, className }) => {
  const { ws } = useContext(GlobalContext);
  const sendMessage = useCallback(
    (data: Record<string, unknown>) => {
      ws.send(JSON.stringify(data));
    },
    [ws]
  );

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

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

  const roadClicked = () => {
    sendMessage({ type: "buy-road" });
    setBuildActive && setBuildActive(false);
  };
  const settlementClicked = () => {
    sendMessage({ type: "buy-settlement" });
    setBuildActive && setBuildActive(false);
  };
  const cityClicked = () => {
    sendMessage({ type: "buy-city" });
    setBuildActive && setBuildActive(false);
  };
  const developmentClicked = () => {
    sendMessage({ 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 (
      <div
        className={`Placard${buildActive ? " Selected" : ""} ${className || ""}`}
        onClick={buildClicked}
        data-type={t}
        style={style}
      >
        {buttons}
      </div>
    );
  }
  return (
    <div className={`Placard${buildActive ? " Selected" : ""} ${className || ""}`} data-type={t} style={style}>
      {count && <div className="Right">{count}</div>}
    </div>
  );
};

export { Placard };
