import React from 'react';
import PropTypes from 'prop-types';
import {performApplyPromoCodeMoReward} from '../../actions';
import PaymentSummaryRow from './payment_summary_row';
import {
  promotionRemoved,
  promotionAdded,
  promotionFailed
} from '../../utils/event_tracking';
import LoadingOverlay from 'shared/components/loader/overlay';
import {connect} from 'react-redux';

class NewPromotionContainer extends React.Component {
  isMounted = false;
  static propTypes = {
    onApply: PropTypes.func,
    cart: PropTypes.object,
    offer_code: PropTypes.String,
    panelMode: PropTypes.String,
    is_editable: PropTypes.String,
    onAddPromoCode: PropTypes.func,
    onSetPromoCode: PropTypes.func
  };
  constructor(props) {
    super(props);
    this.state = {
      offer_code: this.props.cart.attributes.offer_code,
      applyingPromoCode: false,
      appliedPromoCode: false,
      //  check_existing_promotion is true when promotion is selected from users promotion list which include last sucessful persisted promotion.
      checked_existing_promotion: true,
      error:
        this.props.cart.attributes.error &&
        this.props.cart.attributes.error.type &&
        this.props.cart.attributes.error.type.name == 'Invalid Coupon'
          ? this.props.cart.attributes.error.message
          : null
    };
  }

  componentDidMount() {
    this.props.onSetPromoCode(this.props.cart.attributes.offer_code);
    this.isMounted = true;
  }

  componentWillUnmount() {
    this.isMounted = false;
  }
  renderEmpPromotion() {
    if (
      this.props.cart.attributes.employee_promotion &&
      this.props.cart.attributes.offer_code !=
        this.props.cart.attributes.employee_promotion.offer_code
    ) {
      const promotionName = `${this.props.cart.employee_promotion.offer_code}`;
      return (
        <div className="column no-padding">
          <label className="promotion-list radio mojo-title-7 promotion-container user-promotions">
            <input
              type="radio"
              name="promotion"
              defaultChecked={
                this.props.offer_code ==
                this.props.cart.attributes.employee_promotion.offer_code
              }
              value={
                this.props.cart.attributes.employee_promotion.offer_code || ''
              }
              className="promo-radio-input"
              onClick={() =>
                this.assignOfferCode(
                  this.props.cart.attributes.employee_promotion.offer_code,
                  true
                )
              }
            />
            {promotionName}
          </label>
        </div>
      );
    } else {
      return false;
    }
  }

  handleApplyingPromoCode = () => {
    this.setState({
      applyingPromoCode: true
    });
  };

  handleAppliedPromoCode = () => {
    if (this.isMounted) {
      this.setState(
        {
          applyingPromoCode: false,
          appliedPromoCode: true
        },
        () => {
          setTimeout(
            () =>
              this.isMounted ? this.setState({appliedPromoCode: false}) : null,
            1000
          );
        }
      );
    }
  };

  renderError() {
    return (
      <div className="mojo-tagline-error promotion-code-error">
        {this.state.error}
      </div>
    );
  }

  cart_update = async code => {
    try {
      this.handleApplyingPromoCode();
      const attributes = {
        rendered_by: this.props.cart.attributes.rendered_by,
        country_code: this.props.cart.attributes.country_code,
        promotion_code: code
      };
      await this.props
        .onApply({
          type: 'carts',
          id: this.props.cart.id,
          action_type: 'promotion',
          attributes: attributes
        })
        .then(() => this.onUpdateSuccess());
    } catch (e) {
      console.log(e);
    }
  };

  applyPromotion() {
    if (
      this.state.offer_code != undefined &&
      this.state.offer_code.trim() != ''
    ) {
      this.cart_update(this.state.offer_code);
    }
  }

  removePromotion() {
    if (
      this.props.cart.attributes.offer_code ||
      (this.props.cart.attributes.error &&
        this.props.cart.attributes.error['type']['name'] == 'Invalid Coupon')
    ) {
      this.setState({
        removed_offer_code: this.props.cart.attributes.offer_code
      });
      this.cart_update(null);
    } else {
      this.props.onAddPromoCode('DEFAULT');
    }

    this.props.onSetPromoCode(null);
    this.setState({offer_code: ''});
  }

  assignOfferCode(offer_code, existing_promotion) {
    const upcase_offer_code = offer_code && offer_code.toUpperCase();
    this.setState({
      offer_code: upcase_offer_code,
      checked_existing_promotion: existing_promotion
    });
  }

  onUpdateSuccess() {
    const error_on_update =
      this.props.cart.attributes.error &&
      this.props.cart.attributes.error.type &&
      this.props.cart.attributes.error.type.name == 'Invalid Coupon'
        ? this.props.cart.attributes.error.message
        : null;

    // if the applied offer_code matches the input field, we will empty the input field.
    // if there was an error, we want to keep the input so the user can correct
    if (error_on_update == undefined || error_on_update == null) {
      if (!this.state.error && this.state.offer_code.length > 0)
        promotionAdded(this.state.offer_code);
      if (!this.state.error && this.state.offer_code.length === 0)
        promotionRemoved(this.state.removed_offer_code);

      this.props.onAddPromoCode('DEFAULT');
      this.props.onSetPromoCode(this.props.cart.attributes.offer_code);
      this.setState({
        error: null,
        offer_code: ''
      });
      this.handleAppliedPromoCode();
    } else {
      promotionFailed(this.state.offer_code);
      this.setState({
        error: error_on_update,
        applyingPromoCode: false
      });
    }
  }

  checkInput(event) {
    event.target.parentNode.parentNode.childNodes[0].checked = true;
  }

  renderEditViewSection() {
    if (this.props.panelMode == 'ADD_GIFT_CODE' || this.state.error) {
      return (
        <div className="row" key="edit">
          <div className="large-12 medium-12 small-12 column edit-panel white top-shift promo-wrappers promo-container-open">
            {this.state.appliedPromoCode && (
              <div className="confirmation-message-wrapper">
                <div className="confirmation-message">
                  <div
                    className="mojo-tagline-3"
                    data-automation="cart-item-removed"
                  >
                    Has been applied
                  </div>
                </div>
              </div>
            )}
            <LoadingOverlay
              show={this.state.applyingPromoCode}
              label="Applying"
              labelPosition="middle"
            >
              <span
                className="add-gift-code mojo-tagline-price-light padding-right-12
            "
              >
                Promo Code
              </span>
              <div className="add-gift-code-open clearfix">
                <div className="promo-sub-title mojo-tagline-5 margin-bottom-15 column no-padding-left">
                  Limit one per order
                </div>
                {this.renderEmpPromotion()}

                {!this.props.cart.attributes.is_guest &&
                  /* eslint-disable */
                  _.map(
                    this.props.cart.attributes.user_promotions,
                    (up, i) => {
                      return (
                        <div
                          className="column no-padding margin-bottom-20"
                          key={i}
                        >
                          <label className="radio promotion-container font-normal user-promotions mojo-title-7">
                            <input
                              type="radio"
                              value={up.offer_code || ''}
                              defaultChecked={
                                (this.props.offer_code ||
                                  this.props.cart.attributes.offer_code) ==
                                up.offer_code
                              }
                              name="promotion"
                              className="promo-radio-input"
                              onClick={() =>
                                this.assignOfferCode(up.offer_code, true)
                              }
                            />
                            {up.detail}
                          </label>
                        </div>
                      );
                    },
                    this
                  )
                  /* eslint-disable */
                }
                <div className="column no-padding">
                  <label className="pull-left no-padding promotion-container promo-box-container radio margin-bottom-10 promo-input-width">
                    <input
                      type="radio"
                      className="promo-radio-input"
                      name="promotion"
                      onFocus={event =>
                        this.assignOfferCode(
                          this.refs.promoInputField.props.value,
                          false
                        )
                      }
                    />
                    {
                      // eslint-disable-line no-undef
                    }
                    <MojoInputV2
                      ref="promoInputField"
                      style="radio"
                      id="offer_code_text"
                      autoFocus
                      onClick={event => this.checkInput(event)}
                      onChange={event => this.assignOfferCode(event, false)}
                      type="text"
                      showValidationError={Boolean(
                        this.props.cart.attributes.error
                      )}
                      className="open-promo-box"
                      placeholder="Enter Gift Code"
                      value={
                        this.state.checked_existing_promotion
                          ? ''
                          : this.state.offer_code
                      }
                      data-automation="gift-code-input"
                    />
                    {this.state.error && this.renderError()}
                  </label>
                </div>
                {
                  // eslint-disable-line no-undef
                }
                <MojoButtonV2
                  className="button apply-promo-btn margin-top-20 column pull-right large-5 medium-3 small-3"
                  label="Apply"
                  theme="native"
                  onClick={() => this.applyPromotion()}
                />
                <span
                  className="center-button mojo-tagline-button-link margin-top-30 pull-right large-5 medium-3 small-3"
                  onClick={() => this.removePromotion()}
                >
                  Remove
                </span>
              </div>
            </LoadingOverlay>
          </div>
        </div>
      );
    } else {
      return (
        <div className="row">
          <div className="large-12 medium-12 small-12 column edit-panel white top-shift promo-wrappers promo-container">
            <span className="mojo-tagline-price-light padding-right-12 pull-left">
              Promo Code
            </span>
            {this.props.is_editable && (
              <span
                className="pull-left mojo-tagline-button promo-code-option-link"
                onClick={e => this.props.onAddPromoCode('ADD_GIFT_CODE')}
                data-automation="add-gift-code"
              >
                Add
              </span>
            )}
          </div>
        </div>
      );
    }
  }

  renderPromotionContainerCode() {
    if (
      this.props.cart.attributes.offer_code &&
      this.props.panelMode == 'DEFAULT' &&
      !this.props.cart.attributes.invalid_offer_code
    ) {
      return (
        <PaymentSummaryRow
          title={
            this.props.cart.attributes.cost_item_gift_copy
              ? `Promo Code ${this.props.cart.attributes.cost_item_gift_copy}`
              : 'Promo Code'
          }
          sub_label="Edit"
          currency={
            this.props.cart.attributes.payment_summary.promotion_discount &&
            this.props.cart.attributes.payment_summary.promotion_discount
              .currency_html_code
          }
          value={
            this.props.cart.attributes.payment_summary.promotion_discount &&
            this.props.cart.attributes.payment_summary.promotion_discount.human
          }
          negative={
            this.props.cart.attributes.payment_summary.promotion_discount &&
            true
          }
          text_style="mojo-tagline-price-light"
          label_class="gift-total mojo-tagline-price-light"
          onClick={e => this.props.onAddPromoCode('ADD_GIFT_CODE')}
        />
      );
    } else {
      return <div> {this.renderEditViewSection()} </div>;
    }
  }
  render() {
    return (
      <div
        className="mo_promotion_container-v2"
        id="PromotionContainer-v2"
        key="promo"
      >
        {this.renderPromotionContainerCode()}
      </div>
    );
  }
}

NewPromotionContainer.defaultProps = {
  is_editable: true
};

const mapStateToProps = state => ({
  cart: state.api.carts && state.api.carts.data[0],
  panelMode: state.cart_summary.panelMode,
  offer_code: state.cart_summary.giftCode
});

const mapDispatchToProps = dispatch => ({
  onApply: hsh => dispatch(performApplyPromoCodeMoReward(hsh))
});

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