import React, { useEffect, useRef, useState } from 'react';
import useMap from '../../../../hooks/useMap';
import useMarkersFromGuesses from '../../../../hooks/useMarkersFromGuesses';
import styles from './SummaryMap.module.css';

const RoundSelect = ({ rounds, 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
        className={`${styles.tab} ${r === selected ? styles['tab--active'] : ''}`}
        key={r}
        onClick={() => onSelect(r)}
      >
        {r}
      </div>
    ))}
    <div className={styles.tab} onClick={() => onSelect('0')}>
      X
    </div>
  </div>
);

export default ({ players, coords }) => {
  const rounds = Object.keys(coords).length;
  const singleRound = rounds === 1;

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

  // 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(
    () => {
      mapRef.current && 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} selected={roundNum} onSelect={setRoundNum} />}
    </div>
  );
};
