import ms from 'pretty-ms';
import React, { useState } from 'react';
import { createGame } from '../../../domain/apiMethods';
import { MAP_CRUNCH, RANDOM_STREET_VIEW, URBAN } from '../../../domain/genMethods';
import Loading from '../Loading';
import OldDropdown, { Dropdown, Item } from './Dropdown';
import styles from './GameCreationForm.module.css';

export default ({ afterCreate }) => {
  const [ loading, setLoading ] = useState(false);
  const [ timer, setTimer ] = useState(300);
  const [ rounds, setRounds ] = useState(5);
  const [ onlyAmerica, setOnlyAmerica ] = useState(false);
  const [ genMethod, setGenMethod ] = useState(MAP_CRUNCH);

  if (loading) {
    return <Loading />;
  }

  const invalidCombo = genMethod === URBAN && onlyAmerica;

  const onCreateGame = async () => {
    setLoading(true);
    const gameId = await createGame(timer, rounds, onlyAmerica, genMethod);
    if (afterCreate) {
      afterCreate(gameId);
    }
  };

  return (
    <div className={styles.form}>
      <div className={styles.dropdowns}>
        <Dropdown selected={`Round Timer: ${ms(timer * 1000)}`} onSelect={setTimer}>
          <Item value={30}>30 Seconds</Item>
          <Item value={120}>2 Minutes</Item>
          <Item value={300}>5 Minutes</Item>
          <Item value={3600}>1 Hour</Item>
        </Dropdown>
        <OldDropdown
          options={{
            '1 Round': 1,
            '3 Rounds': 3,
            '5 Rounds': 5,
            '10 Rounds': 10
          }}
          onChange={setRounds}
        >
          Rounds: {rounds}
        </OldDropdown>
        <OldDropdown
          options={{
            'All Countries': false,
            'Just America': true
          }}
          onChange={setOnlyAmerica}
        >
          {onlyAmerica ? 'Just America' : 'All Countries'}
        </OldDropdown>
        <OldDropdown
          options={{
            'Map Crunch': MAP_CRUNCH,
            'Random Street View': RANDOM_STREET_VIEW,
            'Urban Centers': URBAN
          }}
          onChange={setGenMethod}
        >
          Generator:{' '}
          {genMethod === MAP_CRUNCH ? 'Map Crunch' : genMethod === RANDOM_STREET_VIEW ? 'RSV' : 'Urban Centers'}
        </OldDropdown>
      </div>
      <button className={styles.start} onClick={onCreateGame} disabled={invalidCombo}>
        {invalidCombo ? 'Incompatible Options' : 'New Game'}
      </button>
    </div>
  );
};
