import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import MiniCartProductRemover from './mini_cart_product_remover';
import LoadingOverlay from 'shared/components/loader/overlay';
import {getRoundedMarkdownPercent} from 'shared/utils/get_rounded_markdown_percent';
import {Image} from 'display-library/Image';
import {miniCartProductClicked} from '../utils/event_tracking';
import classNames from 'classnames';
import {showMultipleSameItemPrice} from 'checkout/utils/line_item_utils';

class MiniCartProductBuilder extends PureComponent {
  isMounted = false;

  static propTypes = {
    carts: PropTypes.object,
    productsArray: PropTypes.array,
    showCorrectPrice: PropTypes.func,
    removing: PropTypes.bool,
    feature_flags: PropTypes.object,
    disableDepositMessage: PropTypes.bool,
    trunkshow_deposit_rate: PropTypes.number,
    showMarkdownNotification: PropTypes.bool
  };

  constructor(props) {
    super(props);

    this.state = {
      cartItemsCount:
        this.props.carts &&
        this.props.carts.attributes &&
        this.props.carts.attributes.cart_items_count,
      removing: false,
      itemRemoved: false
    };
  }

  componentDidMount() {
    this.isMounted = true;
  }

  componentWillUnmount() {
    this.isMounted = false;
  }

  handleRemoving = id => {
    this.checkId = id;
    this.setState({
      removing: true
    });
  };

  handleDeleted = () => {
    if (this.isMounted) {
      this.setState(
        {
          removing: false,
          itemRemoved: true
        },
        () => {
          setTimeout(
            () => (this.isMounted ? this.setState({itemRemoved: false}) : null),
            3000
          );
        }
      );
    }
  };

  sortItemsByMarkdown = items => {
    return items.sort((a, b) => {
      return (
        new Date(b.data.attributes.markdown_last_applied) -
        new Date(a.data.attributes.markdown_last_applied)
      );
    });
  };

  render() {
    let data = undefined;
    const productsArray =
      this.props.feature_flags['bag-markdown-notification'] &&
      this.props.showMarkdownNotification
        ? this.sortItemsByMarkdown(this.props.productsArray)
        : this.props.productsArray;
    return productsArray.map((item, idx) => {
      for (data in item) {
        const itemDetails = item[data].attributes;
        const price = this.props.showCorrectPrice(itemDetails.product_price);
        const deposit = this.props.showCorrectPrice(itemDetails.deposit);
        const markdownPercentage = itemDetails.discounted_price
          ? getRoundedMarkdownPercent(
              itemDetails.retail_price && itemDetails.retail_price.price,
              itemDetails.product_price && itemDetails.product_price.price
            )
          : null;
        const retailPrice = this.props.showCorrectPrice(
          itemDetails.retail_price
        );
        const priceTimesQuantity = showMultipleSameItemPrice(
          itemDetails.quantity,
          itemDetails.product_price
        );
        const dataId = item[data].id;
        const hide_ships_in =
          this.props.feature_flags &&
          this.props.feature_flags['hide-ships-in-copy-checkout'] &&
          (itemDetails.expected_delivery_time &&
            itemDetails.expected_delivery_time.toLowerCase() ===
              'ships in 3-5 days');

        return (
          <div className="cart-item" key={idx}>
            {this.state.itemRemoved && this.checkId == dataId && (
              <div className="confirmation-message-wrapper">
                <div className="confirmation-message">
                  <div
                    className="mojo-tagline-3"
                    data-automation="cart-item-removed"
                  >
                    {itemDetails.name} has been removed.
                  </div>
                </div>
              </div>
            )}
            <LoadingOverlay
              show={this.state.removing && this.checkId == dataId}
              label="Removing"
              labelPosition="middle"
            >
              <div
                className="data-container"
                data-item-moved={
                  this.state.itemRemoved && this.checkId == dataId
                }
              >
                <a
                  className="container-no-x"
                  href={itemDetails.url}
                  onClick={() => miniCartProductClicked(itemDetails)}
                >
                  <div className="image-container">
                    <div className="image">
                      <Image
                        desktop={itemDetails.image_medium}
                        mobile={itemDetails.image_medium}
                      />
                    </div>
                  </div>
                  <div className="info-container">
                    <div className="designer-product-name">
                      <div className="designer">{itemDetails.designer}</div>
                      <div className="name">{itemDetails.name}</div>
                    </div>
                    <div className="price">
                      {itemDetails.discounted_price ? (
                        <div className="original-amount">
                          <span className="previous-amount strike-text">
                            {retailPrice}&nbsp;
                          </span>
                          {itemDetails.quantity > 1
                            ? priceTimesQuantity
                            : price}
                          {this.props.feature_flags[
                            'bag-markdown-notification'
                          ] && (
                            <span className="markdown-percentage-text">
                              Save {markdownPercentage}%
                            </span>
                          )}
                        </div>
                      ) : (
                        <span className="original-amount">
                          {itemDetails.quantity > 1 ? retailPrice : price}
                        </span>
                      )}
                      <span className="available-inventory">
                        {!this.props.disableDepositMessage &&
                          itemDetails.deposit.price !== 0 && (
                            <span className="previous-amount deposit-price">
                              &nbsp;({deposit} Deposit)
                            </span>
                          )}
                      </span>
                      {itemDetails.vat_included_message && (
                        <div className="name">
                          {itemDetails.vat_included_message}
                        </div>
                      )}
                    </div>

                    <div className="other-info">
                      <div className="item-info size">
                        <span>Size:&nbsp;</span>
                        <span className="light">{itemDetails.size}&nbsp;</span>
                        {itemDetails.low_stock_alert && (
                          <span
                            className={classNames('light low-stock-alert', {
                              'low-stock-alert--red': this.props.feature_flags[
                                'red-low-stock-alert'
                              ]
                            })}
                          >
                            {itemDetails.low_stock_alert}
                          </span>
                        )}
                      </div>
                      <div className="item-info qty">
                        <span>Qty:&nbsp;</span>
                        <span className="light">
                          {itemDetails.quantity}&nbsp;
                        </span>
                      </div>
                    </div>
                    {itemDetails.expected_delivery_time && !hide_ships_in && (
                      <div className="delivery-date">
                        {itemDetails.expected_delivery_time}
                      </div>
                    )}
                    {!this.props.disableDepositMessage &&
                      itemDetails.deposit.price !== 0 && (
                        <div className="delivery-date">
                          <div className="name">RESERVE TODAY</div>
                          <div className="name">
                            An advance payment of{' '}
                            {this.props.trunkshow_deposit_rate * 100}% is
                            required at checkout.
                          </div>
                        </div>
                      )}
                  </div>
                </a>
                <MiniCartProductRemover
                  dataId={dataId}
                  item={item[data]}
                  cartItemsCount={this.state.cartItemsCount}
                  handleRemoving={this.handleRemoving}
                  handleDeleted={this.handleDeleted}
                  itemQuantity={itemDetails.quantity}
                />
              </div>
            </LoadingOverlay>
          </div>
        );
      }
    });
  }
}

export default MiniCartProductBuilder;
