import { useCallback, useState } from "react";
import { dispatch } from "../../../../domain/gameStore";
import { reverseGeocode } from "../../../../domain/geocoding";
import ClickMarkerMap from "./ClickMarkerMap";
import styles from "./GuessPane.module.css";
import RoundTimer from "./RoundTimer";
import useMapResizeKeybindings from "./useMapResizeKeybindings";

const mapSizeOpts = {
  small: styles["pane--small"],
  medium: styles["pane--medium"],
  big: styles["pane--big"],
};

const toggleMapSize = larger => b =>
  b === "big" || b === "medium" ? "small" : larger;

const GuessPane = () => {
  const [selectedPoint, setSelectedPoint] = useState(null);
  const [submitted, setSubmitted] = useState(false);
  const [mapSize, setMapSize] = useState("small");
  const toggleBig = useCallback(() => setMapSize(toggleMapSize("big")), []);
  const toggleMed = useCallback(() => setMapSize(toggleMapSize("medium")), []);
  useMapResizeKeybindings(toggleBig);

  const handleSubmitGuess = async () => {
    setSubmitted(true);
    if (!submitted) {
      await dispatch.submitGuess(
        selectedPoint && {
          country: await reverseGeocode(selectedPoint),
          ...selectedPoint,
        }
      );
    }
  };

  return (
    <div className={`${styles.pane} ${mapSizeOpts[mapSize]}`}>
      <button
        type="button"
        className={styles.submit}
        onClick={handleSubmitGuess}
        disabled={submitted || selectedPoint === null}
      >
        Submit Guess
      </button>
      <ClickMarkerMap onMarkerMoved={setSelectedPoint} />
      <RoundTimer onTimeout={handleSubmitGuess} />
      <div
        className={styles.resize}
        onClick={toggleBig}
        role="button"
        tabIndex="0"
        onKeyDown={({ key }) => {
          if (key === "Enter") {
            toggleBig();
          }
        }}
      >
        {mapSize === "small" ? "↗️" : "↙️"}
      </div>
      <div
        className={`${styles.resize} ${styles["resize--medium"]}`}
        onClick={toggleMed}
        role="button"
        tabIndex="0"
        onKeyDown={({ key }) => {
          if (key === "Enter") {
            toggleMed();
          }
        }}
      >
        {mapSize === "small" ? "➡️" : "⬅️"}
      </div>
    </div>
  );
};

export default GuessPane;
