import { useRef } from "react";
import {
  dispatch,
  useCurrentRound,
  useLastRound,
} from "../../../domain/gameStore";
import { usePlayers } from "../../../hooks/useGameInfo";
import useMap from "../../../hooks/useMap";
import useMarkersFromGuesses from "../../../hooks/useMarkersFromGuesses";
import usePreventNavigation from "../../../hooks/usePreventNavigation";
import DelayedButton from "../../util/DelayedButton";
import styles from "./RoundSummary.module.css";
import useClickToCheckScore from "./useClickToCheckScore";

export const NextRoundButton = () => {
  // check the current round to see if game is done
  const currentRound = useCurrentRound();

  return currentRound ? (
    <DelayedButton
      autoFocus
      buttonClass={styles.next}
      onEnd={dispatch.startRound}
      countDownFormatter={rem => `Click to cancel, ${rem}s...`}
    >
      Next Round
    </DelayedButton>
  ) : (
    <button
      type="button"
      autoFocus
      className={styles.next}
      onClick={() => dispatch.goToSummary()}
    >
      View Summary
    </button>
  );
};

const RoundSummary = () => {
  // get the info about the last round
  const { roundNum, score, totalScore, targetPoint } = useLastRound();

  // create the map
  const mapDivRef = useRef(null);
  const mapRef = useMap(mapDivRef, targetPoint.lat, targetPoint.lng, 4);

  // live update with all the scores
  const players = usePlayers();

  // add the player guess markers
  useMarkersFromGuesses(mapRef, players, roundNum, targetPoint);

  // let the current player click the map to see a possible score
  useClickToCheckScore(mapRef, targetPoint);

  // warn the user if they navigate away
  usePreventNavigation();

  return (
    <div>
      <div className={styles.map} ref={mapDivRef} />
      <div className={styles.panel}>
        <span className={styles.score}>
          Score for Round {roundNum}: {score}
        </span>
        <span className={styles.score}>Running Total: {totalScore}</span>
        <NextRoundButton />
      </div>
    </div>
  );
};

export default RoundSummary;
