import { useEffect, useRef, useState } from "react";
import flagLookup from "../../../../domain/flagLookup";
import { useGameConfig } from "../../../../hooks/useGameInfo";
import useMap from "../../../../hooks/useMap";
import useMapBounds from "../../../../hooks/useMapBounds";
import useMarkersFromGuesses from "../../../../hooks/useMarkersFromGuesses";
import styles from "./SummaryMap.module.css";

export const RoundSelect = ({ rounds, coords, selected, onSelect }) => (
  <div className={styles.tabs}>
    {
      // fun fact: es6 doesn't have a range(x) function
      Array.from(Array(rounds).keys())
        .map(r => (r + 1).toString())
        .map(r => (
          <div
            role="button"
            tabIndex="0"
            onKeyDown={({ key }) => {
              if (key === "Enter") {
                onSelect(r);
              }
            }}
            className={`${styles.tab} ${
              r === selected ? styles["tab--active"] : ""
            }`}
            key={r}
            onClick={() => onSelect(r)}
          >
            {r} - {flagLookup(coords[r].country)}
          </div>
        ))
    }
    <div
      className={styles.tab}
      role="button"
      tabIndex="0"
      onClick={() => onSelect("0")}
      onKeyDown={({ key }) => {
        if (key === "Enter") {
          onSelect("0");
        }
      }}
    >
      X
    </div>
  </div>
);

const SummaryMap = ({ players, coords }) => {
  const rounds = Object.keys(coords).length;
  const singleRound = rounds === 1;
  const { countryLock } = useGameConfig();

  // create the map
  const mapDivRef = useRef(null);
  const mapRef = useMap(mapDivRef, 0, 0, 1);
  useMapBounds(mapRef, countryLock);

  // set up round number selection
  const [roundNum, setRoundNum] = useState("0");
  const roundActive = singleRound ? "1" : roundNum;

  // get the target point
  const targetPoint = coords?.[roundActive] ?? null;

  // put the markers on the map
  useMarkersFromGuesses(mapRef, players, roundActive, targetPoint);

  // scroll the map to the target point
  useEffect(() => {
    if (mapRef.current) {
      // TODO maybe pack this up with setRoundNum and pass as onSelect
      mapRef.current.panTo(targetPoint ?? { lat: 0, lng: 0 });
    }
  }, [mapRef, targetPoint]);

  return (
    <div className={styles.container}>
      <div className={styles.map} ref={mapDivRef} />
      {singleRound || (
        <RoundSelect
          rounds={rounds}
          coords={coords}
          selected={roundNum}
          onSelect={setRoundNum}
        />
      )}
    </div>
  );
};

export default SummaryMap;
