import { useState, useEffect, useRef, forwardRef } from 'react';
import { dispatch } from '../../../domain/gameStore';
import { hasSavedGameInfo } from '../../../domain/localStorageMethods';
import DelayedButton from '../../util/DelayedButton';
import GameCreationForm from '../../util/GameCreationForm';
import styles from './HomePage.module.css';
import { CSSTransition } from 'react-transition-group';

const Rejoin = forwardRef((_, ref) => (
  <div className={styles.rejoinSection} ref={ref}>
    <span className={styles.rejoinLabel}>Looks like you were in a game before that you didn't finish!</span>
    <DelayedButton onEnd={() => dispatch.rejoinGame()} countDownFormatter={(rem) => `Rejoining in ${rem}s...`}>
      Rejoin Game?
    </DelayedButton>
  </div>
));

const HomePage = () => {
  const [hasSavedInfo, setHasSavedInfo] = useState(false);
  useEffect(() => {
    hasSavedGameInfo().then(setHasSavedInfo)
  }, []);
  const transitionRef = useRef(null);

  return (
    <div className={styles.page}>
      <CSSTransition nodeRef={transitionRef} in={hasSavedInfo} mountOnEnter unmountOnExit timeout={500} classNames="fade">
        <Rejoin ref={transitionRef}/>
      </CSSTransition>
      <GameCreationForm afterCreate={(gameId) => dispatch.goToLobby(gameId)} />
    </div>
  );
};

export default HomePage;