import React, { Component } from 'react';
import * as ReactDOM from 'react-dom';
import PokemonList from '../components/pokemon-list';
import ConnectModal from '../components/connect-modal';
import Menu from '../components/menu';

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

    this.state = {
      pokemonList: [],
      open: false,
      pokemonWantList: [],
    };
  }

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

  render() {
    const {
      pokemonList, pokemonWantList, selectedId, linked,
    } = this.state;
    let { open } = this.state;

    const handleAddPokemonClick = () => () => {
      window.location.href = '/chose.html?type=have';
    };

    const onSelectPokemon = (selected, url, id, deselect) => {
      fetch('/api/stored-pokemon-want')
        .then(response => response.json())
        .then((data) => {
          open = true;
          fetch('/api/linked-stored-pokemon')
            .then(response => response.json())
            .then((data2) => {
              this.setState({
                open, deselect, pokemonWantList: data, selectedId: id, linked: data2,
              });
            });
        });
    };

    const onDeselectPokemon = () => {
      const { deselect } = this.state;
      open = false;
      deselect();
      this.setState({ open, deselect: undefined });
    };

    const handleLinkWantAndNeed = groupId => () => {
      fetch('api/linked-stored-pokemon', {
        method: 'POST',
        body: JSON.stringify({
          group_id: groupId,
          selected_id: selectedId,
        }),
      }).then(() => {});
    };


    return (
      <div>
        <Menu active={0} />
        <PokemonList pokemonList={pokemonList} onSelectPokemon={onSelectPokemon} />
        <button style={{ fontSize: '10em' }} type="button" onClick={handleAddPokemonClick()}>Add</button>
        <ConnectModal
          pokemonWantList={pokemonWantList}
          open={open}
          onDeselectPokemon={onDeselectPokemon}
          handleLinkWantAndNeed={handleLinkWantAndNeed}
          linked={linked}
          selectedId={selectedId}
        />
      </div>
    );
  }
}


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