/* eslint-disable jsx-a11y/label-has-for */
import React, { Component } from 'react';
import style from './AddProduct.module.css';
import injector from './../lib/components/Injector';


class AddProduct extends Component {
  constructor(props) {
    console.log('new AddProduct');
    super(props);
    this.state = { ...props.state };
  }

  setPrice(event) {
    event.preventDefault();
    const price = event.target.value;
    console.log('setPrice:', price, this.props.state);
    this.props.actions.setPrice(price)
      .then(() => {
        this.setState({ price });
      });
  }

  setName(event) {
    event.preventDefault();
    const name = event.target.value;
    console.log('setName:', name, this.props.state);
    this.props.actions.setName(name)
      .then(() => {
        this.setState({ name });
      });
  }

  addProduct() {
    const { actions, state } = this.props;
    Promise.all([
      actions.addProduct({
        name: state.name,
        price: state.price,
        id: Math.floor(Math.random() * 1000),
      }),
      actions.setName(''),
      actions.setPrice(0),
    ]).then(() => this.setState(this.props.state));
  }

  render() {
    const { name, price } = this.state;

    return (
      <div className={style.formContainer}>
        <div className={style.formRow}>
          <label htmlFor="product-name">Name</label>
          <input id="product-name" value={name} type="text" onChange={e => this.setName(e)} />
        </div>
        <div className={style.formRow}>
          <label htmlFor="product-price">Price</label>
          <input id="product-price" value={price} type="text" onChange={e => this.setPrice(e)} />
        </div>
        <hr />
        <div className={style.formRow}>
          <button onClick={() => this.addProduct()}>
            Add Product
          </button>
        </div>
      </div>
    );
  }
}

export default injector(AddProduct);
