import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {miniCartProductRemoved} from '../utils/event_tracking';
import {performDeleteLineItem} from 'mini_cart/actions';

class MiniCartProductRemover extends PureComponent {
  static propTypes = {
    cart: PropTypes.object.isRequired,
    dataId: PropTypes.string,
    item: PropTypes.object,
    onDelete: PropTypes.func,
    cartItemsCount: PropTypes.number,
    handleRemoving: PropTypes.func,
    handleDeleted: PropTypes.func,
    itemQuantity: PropTypes.number
  };

  constructor(props) {
    super(props);
  }

  handleRemoveItem = async (id, qty) => {
    try {
      if (!this.props.cart) return;
      this.props.handleRemoving(id);
      await this.props.onDelete({
        id: id,
        qty: qty,
        country_code: this.props.cart.attributes.country_code
      });
      this.props.handleDeleted();
      miniCartProductRemoved(this.props.item.attributes);
    } catch (e) {
      this.onError(e);
    }
  };

  onError(e) {
    // eslint-disable-next-line no-console
    console.error('remove from bag error', e);
  }

  render() {
    return (
      <div className="remove">
        <span
          onClick={() =>
            this.handleRemoveItem(this.props.dataId, this.props.itemQuantity)
          }
        >
          <span className="mo-web-icon-close" />
        </span>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    cart: state.api.carts && state.api.carts.data[0]
  };
};

const mapDispatchToProps = dispatch => ({
  onDelete: hsh => {
    dispatch(performDeleteLineItem(hsh));
  }
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(MiniCartProductRemover);
