import React, { useEffect } from "react";
import useCameraModeStore, {
  usePlayButtonStore,
} from "../../../store/usePlayButtonStore";
import useModuleStore from "../../../store/useModuleStore";
import { PlayIcon } from "../../icons/ShortcutIcons";
import InputToggle from "../../ui/inputs/InputToggle";
import { EyeCloseIcon, WalkIcon } from "../../icons/ExportCommonIcons";
import { ExitIcon } from "../../icons/SimulationIcons";
import { useCamMode } from "../../../store/builder/store";
import { usePlayerStore } from "../../../store/useUIToggleStore";

const ControlsPlayer: React.FC = () => {
  const { setIsPlaying } = usePlayButtonStore();
  const { activeModule } = useModuleStore();
  const { walkMode, toggleWalkMode } = useCameraModeStore();
  const { hidePlayer, setHidePlayer } = usePlayerStore();
  const { camMode } = useCamMode();

  const changeCamMode = () => {
    toggleWalkMode();
    echo.log("switch camera mode to first person");
    // Simulate "/" keypress
    const slashKeyEvent = new KeyboardEvent("keydown", {
      key: "/",
      code: "Slash",
      keyCode: 191, // for compatibility
      which: 191,
      bubbles: true,
      cancelable: true,
    });
    document.dispatchEvent(slashKeyEvent);
  };
  useEffect(() => {
    if (camMode === "ThirdPerson") {
      toggleWalkMode();
    } else return;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [camMode]);

  return (
    <div className={`controls-player-container${hidePlayer ? " hide" : ""}`}>
      {!hidePlayer && (
        <div className="controls-left">
          <PlayIcon />
          <div className="label">Running {activeModule}...</div>
        </div>
      )}

      <div className="controls-right">
        {!hidePlayer && activeModule === "builder" && (
          <div className="walkMode-wrapper">
            <WalkIcon />
            <InputToggle
              value={walkMode}
              inputKey="1"
              label="Walk Mode"
              onClick={changeCamMode}
            />
          </div>
        )}
        <button
          id="controls-player-play-button"
          className={`btn-wrapper${hidePlayer ? " hide" : ""}`}
          onClick={() => setIsPlaying(false)}
        >
          <div className="icon">
            <ExitIcon />
          </div>
          {!hidePlayer && "Exit"}
        </button>
        <button
          className={`btn-wrapper${hidePlayer ? " hide" : ""}`}
          id="hide-btn"
          onClick={() => {
            setHidePlayer(!hidePlayer);
          }}
        >
          <div className="icon">
            <EyeCloseIcon />
          </div>
          {!hidePlayer && "Hide"}
        </button>
      </div>
    </div>
  );
};

export default ControlsPlayer;
