import React, { Component } from 'react';
import * as ReactDOM from 'react-dom';
import Menu from '../components/menu';
import WantGroup from '../components/want-group';

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

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

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

  render() {
    const { pokemonWantList } = this.state;

    const handleEditPokemonClick = wantGroupId => () => {
      window.location.href = `/chose.html?type=want&want_group_id=${wantGroupId}`;
    };

    const handleDeletePokemonClick = wantGroupId => () => {
      fetch('api/stored-pokemon-want', {
        method: 'DELETE',
        body: JSON.stringify({ wantGroupId }),
      }).then(response => response.json())
        .then((data) => {
          this.setState({ pokemonWantList: data });
        });
    };
    const handleAddPokemonClick = () => () => {
      fetch('api/stored-pokemon-want', {
        method: 'POST',
      }).then(response => response.json())
        .then((data) => {
          this.setState({ pokemonWantList: data });
        });
    };

    const wantGroups = [];
    pokemonWantList.forEach((wantGroup) => {
      wantGroups.push(<WantGroup
        pokemonList={wantGroup.pokemons}
        groupId={wantGroup.id}
        groupName={wantGroup.group_name}
        handleEditPokemonClick={handleEditPokemonClick}
        handleDeletePokemonClick={handleDeletePokemonClick}
      />);
    });

    return (
      <div>
        <Menu active={1} />
        {wantGroups}
        <button className="addButton" style={{ fontSize: '10em' }} type="button" onClick={handleAddPokemonClick()}>Add</button>
      </div>
    );
  }
}

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