import React, { useState } from 'react';
import styled from 'styled-components';
import Loading from '../../util/Loading';
import GuessPane from "./GuessPane";
import PositionedStreetView from "./PositionedStreetView";
import useRoundInfo from "../../../hooks/useRoundInfo";
import { dispatch } from '../../../domain/gameStore';
import { useTimerFromLocalStorage, clearTimerFromLocalStorage } from '../../../domain/localStorageMethods';
import usePreventNavigation from '../../../hooks/usePreventNavigation';

const Container = styled.div`
  height: 100%;
  width: 100%;
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: center;

  @media only screen and (min-width: 600px) and (min-height: 600px) {
    display: block;
    position: relative;
    margin-bottom: 2px;
    margin-right: 2px;
  }
`

const StreetViewWrapper = styled.div`
  height: 100%;
  width: 100%;
  margin-bottom: 2px;
  flex: 3;
`

export default () => {
  // warn the user if they navigate away
  usePreventNavigation();
  
  const [submitDisabled, setSubmitDisabled] = useState(false);
  const [selectedPoint, setSelectedPoint] = useState(null);
  const [finished, roundInfo] = useRoundInfo();

  if (finished) {
    dispatch.goToSummary();
    return <Loading/>
  }

  const { currentRound, targetPoint, roundSeconds } = roundInfo;
  if (!currentRound || !targetPoint || !roundSeconds) {
    return <Loading/>
  }

  const storedTimer = useTimerFromLocalStorage();

  const handleSubmitGuess = async () => {
    setSubmitDisabled(true);
    await dispatch.submitGuess(selectedPoint, currentRound, targetPoint);
    clearTimerFromLocalStorage();
  }

  return (
    <Container>
      <StreetViewWrapper>
          <PositionedStreetView position={targetPoint} />
      </StreetViewWrapper>
      <GuessPane
        roundSeconds={storedTimer ?? roundSeconds}
        onTimeout={handleSubmitGuess}
        onSelectPoint={setSelectedPoint}
        onSubmitGuess={handleSubmitGuess}
        submitDisabled={submitDisabled || selectedPoint === null}
      />
    </Container>
  );
}
