import { useState, useEffect } 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';

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');

  useEffect(() => {
    const listener = event => {
      if (event.code === 'Escape') {
        setMapSize(toggleMapSize('big'));
      }
    }
    document.addEventListener('keydown', listener, false);
    return () => document.removeEventListener('keydown', listener, false);

  }, [])

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

  return (
    <div className={`${styles.pane} ${mapSizeOpts[mapSize]}`}>
      <button
        className={styles.submit}
        onClick={handleSubmitGuess}
        disabled={submitted || selectedPoint === null}
      >
        Submit Guess
      </button>
      <ClickMarkerMap onMarkerMoved={setSelectedPoint} />
      <RoundTimer onTimeout={handleSubmitGuess} />
      <div className={styles.resize} onClick={() => setMapSize(toggleMapSize('big'))}>
        { mapSize === 'small' ? '↗️' : '↙️' }
      </div>
      <div className={`${styles.resize} ${styles['resize--medium']}`} onClick={() => setMapSize(toggleMapSize('medium'))}>
        { mapSize === 'small' ? '➡️' : '⬅️' }
      </div>
    </div>
  );
};

export default GuessPane;