import React, { Component } from 'react';
import * as ReactDOM from 'react-dom';
import * as queryString from 'query-string';
import PokemonList from '../components/pokemon-list';
import Menu from '../components/menu';

class App extends Component {
  constructor(props) {
    super(props);

    const params = queryString.parse(location.search);

    const { type } = params;
    const wantGroupId = params.want_group_id;

    this.state = {
      pokemonList: [],
      selectedPokemon: new Map(),
      type,
      wantGroupId,
    };
  }

  componentDidMount() {
    fetch('/api/available-pokemon')
      .then(response => response.json())
      .then((data) => {
        this.setState({ pokemonList: data.pokemons });
      });
  }

  render() {
    const {
      pokemonList, selectedPokemon, type, wantGroupId,
    } = this.state;

    const handleDoneClick = () => () => {
      const pokemons = [];
      selectedPokemon.forEach((pokemon) => {
        pokemons.push({
          id: pokemon.id,
          url: pokemon.url,
        });
      });
      fetch(`api/stored-pokemon?type=${type}&want-group-id=${wantGroupId}`, {
        method: 'POST',
        body: JSON.stringify(pokemons),
      }).then(() => {
        if (type === 'want') {
          window.location.href = '/want.html';
        } else {
          window.location.href = '/index.html';
        }
      });
    };

    const onSelectPokemon = (selected, url, id) => {
      if (selected) {
        selectedPokemon.set(id, { id, url });
      } else {
        selectedPokemon.delete(id);
      }
      this.setState({ selectedPokemon });
    };

    return (
      <div>
        <Menu />
        <PokemonList pokemonList={pokemonList} onSelectPokemon={onSelectPokemon} />
        <button type="button" style={{ fontSize: '10em' }} onClick={handleDoneClick()}>Done</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('main'));
