import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import LoadingOverlay from 'shared/components/loader/overlay';
import {Image} from 'display-library/Image';
import {
  productUpdate,
  checkoutProductClicked,
  cartItemRemoved
} from '../../utils/event_tracking';
import classNames from 'classnames';
import {performUpdateCartEntity} from '../../actions';
import {performDeleteLineItem} from 'mini_cart/actions';
import {
  getErrorMessage,
  renderExcessShipping,
  renderGiftPackagingMessage,
  showMultipleSameItemPrice
} from '../../utils/line_item_utils';
import ShippingAddressSelect from '../user_summary/shipping_address/ShippingAddressSelect';
import {TSCountdownTimer} from 'display-library/TSCountdownTimer';

class CheckoutItemBuilder extends PureComponent {
  isMounted = false;

  static propTypes = {
    cart: PropTypes.object,
    productsArray: PropTypes.array,
    showCorrectPrice: PropTypes.func,
    removing: PropTypes.bool,
    feature_flags: PropTypes.object,
    disableDepositMessage: PropTypes.bool,
    trunkshow_deposit_rate: PropTypes.number,
    updateCartEntity: PropTypes.func,
    onDelete: PropTypes.func,
    isMobile: PropTypes.boolean
  };

  constructor(props) {
    super(props);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    this.state = {
      removing: false,
      itemRemoved: false,
      applying_save_for_later: false,
      itemMovedToSFL: false,
      sizeChanging: false,
      qtyChanging: false,
      sizeChanged: false,
      qtyChanged: 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
          );
        }
      );
    }
  };

  handleSaveForLater = id => {
    this.checkId = id;
    this.setState({
      applying_save_for_later: true
    });
  };

  handleMovedToSfl = () => {
    if (this.isMounted) {
      this.setState(
        {
          applying_save_for_later: false,
          itemMovedToSFL: true
        },
        () => {
          setTimeout(
            () =>
              this.isMounted ? this.setState({itemMovedToSFL: false}) : null,
            3000
          );
        }
      );
    }
  };

  handleSizeQtyUpdate = updateType => {
    if (this.isMounted) {
      if (updateType == 'update_size') {
        this.setState(
          {
            sizeChanging: false,
            sizeChanged: true
          },
          () => {
            setTimeout(
              () =>
                this.isMounted ? this.setState({sizeChanged: false}) : null,
              3000
            );
          }
        );
      } else {
        this.setState(
          {
            qtyChanging: false,
            qtyChanged: true
          },
          () => {
            setTimeout(
              () =>
                this.isMounted ? this.setState({qtyChanged: false}) : null,
              3000
            );
          }
        );
      }
    }
  };

  renderDisabledSize = attributes => {
    return (
      attributes.errors &&
      (attributes.errors.type === 'SHORT_SOLD_OUT_MESSAGE' ||
        attributes.errors.type === 'SHORT_PRODUCT_EXPIRED_MESSAGE')
    );
  };

  renderDisabledQty = attributes => {
    return (
      attributes.errors &&
      (attributes.errors.type === 'SHORT_SOLD_OUT_MESSAGE' ||
        attributes.errors.type === 'SHORT_PRODUCT_EXPIRED_MESSAGE')
    );
  };

  sku_id_for_size = (size, size_options) => {
    const selected_option = size_options.filter(
      option => option.value == size
    )[0];

    if (selected_option) {
      return selected_option.sku_id;
    } else {
      return null;
    }
  };

  trackUpdateProduct = (variantId, updateType, oldValue, newValue) => {
    const updatedField = updateType === 'update_qty' ? 'quantity' : 'size';
    productUpdate(variantId, updatedField, oldValue, newValue, 'checkout');
  };

  saveForLater = async cart_item_id => {
    // eslint-disable-next-line no-undef
    if (SiteConstants.is_guest || !SiteConstants.current_user) {
      window && window.moda.authDialogs.signIn();
      return;
    }
    const cart = this.props.cart;
    const attributes = {
      cart_id: cart.id,
      rendered_by: cart.attributes.rendered_by,
      type: 'SavedItem',
      country_code: cart.attributes.country_code
    };

    this.handleSaveForLater(cart_item_id);
    await this.props
      .updateCartEntity({
        type: 'line_items',
        id: cart_item_id,
        attributes: attributes,
        skip_analytics: true
      })
      .then(result => {
        this.handleMovedToSfl();
        this.onDeleteSuccess(result);
      })
      .catch(error => {
        // eslint-disable-next-line no-unused-vars
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        console.log(error);
      });
  };

  updateQuantitySize = async (
    cart_item,
    sku_id,
    quantity,
    updateType,
    oldValue
  ) => {
    const cart = this.props.cart;
    const attributes = {
      cart_id: cart.id,
      sku_id: sku_id,
      quantity: quantity,
      rendered_by: cart.attributes.rendered_by,
      type: 'CartItem',
      label: updateType,
      back_in_stock: cart_item.attributes.back_in_stock,
      country_code: cart.attributes.country_code
    };
    const size_options = cart_item.attributes.size_options || [];
    const correctSize = size_options.filter(size => size.sku_id === sku_id)[0];
    if (correctSize) attributes.size = correctSize.value;

    const newValue = updateType === 'update_qty' ? quantity : correctSize.value;
    this.checkId = cart_item.id;
    if (updateType == 'update_size') {
      this.setState({
        sizeChanging: true
      });
    } else if (updateType == 'update_qty') {
      this.setState({
        qtyChanging: true
      });
    }
    await this.props
      .updateCartEntity({
        type: 'cart_items',
        id: cart_item.id,
        attributes: attributes
      })
      .then(() =>
        this.onUpdateSuccess(
          cart_item.attributes.variant_id,
          updateType,
          oldValue,
          newValue
        )
      )
      .catch(error => {
        // eslint-disable-next-line no-unused-vars
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        console.log(error);
      });
  };

  onUpdateSuccess = (variant_id, updateType, oldValue, newValue) => {
    console.log('updated');
    this.handleSizeQtyUpdate(updateType);
    this.trackUpdateProduct(variant_id, updateType, oldValue, newValue);
  };

  handleRemoveItem = async (id, qty, item) => {
    if (!this.props.cart) return;
    this.handleRemoving(id);
    await this.props
      .onDelete({
        id: id,
        qty: qty,
        country_code: this.props.cart.attributes.country_code
      })
      .then(result => {
        this.handleDeleted();
        cartItemRemoved(item, 'checkout');
        this.onDeleteSuccess(result);
      })
      .catch(error => {
        //eslint-disable-next-line no-unused-vars
        //eslint-disable-next-line @typescript-eslint/no-unused-vars
        console.log(error);
      });
  };

  onDeleteSuccess(cart) {
    if (cart.attributes.cart_items_count == 0) {
      window.location.href = '/shopping-bag';
    }
  }

  showQtyError = attributes => {
    return (
      attributes.errors &&
      attributes.errors.type === 'SHORT_QUANTITY_EXCEEDED_MESSAGE' &&
      attributes.quantity > attributes.max_quantity &&
      attributes.size_options.find(
        s => s.value === attributes.size && s.quantity !== 0
      ) !== undefined
    );
  };

  showSizeError = attributes => {
    return (
      attributes.errors &&
      attributes.errors.type === 'SHORT_SIZE_SOLD_OUT_MESSAGE' &&
      attributes.size_options.find(
        s => s.value === attributes.size && s.quantity !== 0
      ) === undefined
    );
  };
  renderTimer = attributes => {
    if (attributes.is_trunkshow && !this.tsEnded(attributes)) {
      return (
        <TSCountdownTimer
          endingText="Trunkshow ends in"
          startingText="Trunkshow starts in"
          activeEnd={attributes.active_end_i * 1000}
          activeStart={attributes.active_start_i * 1000}
          renderedBy={this.props.cart.attributes.rendered_by}
        />
      );
    }
  };

  tsEnded = attributes => {
    return (
      attributes.errors &&
      attributes.errors.type == 'SHORT_PRODUCT_EXPIRED_MESSAGE' &&
      attributes.is_trunkshow
    );
  };

  renderTSErrorMessage = cart_item => {
    if (this.tsEnded(cart_item.attributes)) {
      return (
        // eslint-disable-next-line no-undef
        <div className={classNames({mobile: this.props.isMobile})}>
          <div className="column large-12 medium-12 small-12 no-padding error-container">
            <span className="mojo-error-message error-message error-message-margin">
              Trunkshow has ended.{' '}
              <span
                className="save-later-link"
                onClick={() => {
                  this.saveForLater(cart_item.id);
                }}
              >
                Save for later{' '}
              </span>{' '}
              to be notified when item is back in stock.
            </span>
          </div>
        </div>
      );
    }
  };

  renderReserveToday = attributes => {
    if (!attributes.pay_in_full) {
      const trunkshow_deposit_rate =
        // eslint-disable-next-line no-undef
        typeof SiteConstants != 'undefined'
          ? // eslint-disable-next-line no-undef
            SiteConstants.trunkshow_deposit_rate
          : 0.5;

      return (
        <div className="mojo-tagline-4 expected-delivery-time">
          <div> RESERVE TODAY</div>
          An advance payment of {trunkshow_deposit_rate * 100}% is required at
          checkout. The remaining balance will be charged when item ships.
        </div>
      );
    }
  };

  renderExpectedDeliveryDate = attributes => {
    const hide_ships_in =
      this.props.feature_flags &&
      this.props.feature_flags['hide-ships-in-copy-checkout'] &&
      attributes.expected_delivery_time &&
      attributes.expected_delivery_time.toLowerCase() === 'ships in 3-5 days';

    if (
      (attributes.expected_delivery_time ||
        attributes.expected_shipping_details) &&
      !hide_ships_in
    ) {
      return (
        <div
          className="mojo-tagline-4 expected-delivery-time"
          data-automation="expected-delivery-time"
        >
          {attributes.expected_delivery_time ||
            attributes.expected_shipping_details}
        </div>
      );
    }
  };

  renderReturnPolicy = attributes => {
    if (attributes.return_policy) {
      return (
        <div
          className="mojo-tagline-4 return-policy"
          data-automation="return-policy"
        >
          {attributes.return_policy}
        </div>
      );
    }
  };

  renderBtqErrorMessage = cart_item => {
    const attributes = cart_item.attributes;
    if (
      attributes.errors &&
      attributes.errors.type == 'SHORT_SOLD_OUT_MESSAGE' &&
      !attributes.is_trunkshow
    ) {
      return (
        // eslint-disable-next-line no-undef
        <div className={classNames({mobile: this.props.isMobile})}>
          <div className="column large-12 medium-12 small-12 no-padding error-container">
            <span className="mojo-error-message error-message error-message-margin">
              This item is no longer available.{' '}
              <span
                className="save-later-link"
                onClick={() => {
                  this.saveForLater(cart_item.id);
                }}
              >
                Save for later{' '}
              </span>{' '}
              to be notified when item is back in stock.
            </span>
          </div>
        </div>
      );
    }
  };

  renderErrorMessage = attributes => {
    if (attributes.errors) {
      return (
        <div
          className={classNames('error-message-main-container', {
            // eslint-disable-next-line no-undef
            mobile: this.props.isMobile
          })}
        >
          <div className="column large-12 medium-12 small-12 no-padding error-container">
            <span className="mojo-error-message error-message error-message-margin">
              {getErrorMessage(attributes)}
            </span>
          </div>
        </div>
      );
    }
  };

  renderConditionalDiv = attributes => {
    return (
      attributes.excess_shipping ||
      attributes.gift_packaging_message ||
      attributes.rewards_message ||
      attributes.customer_delivery_notes
    );
  };

  renderConditionalMessages = attributes => {
    const ifRenderConditionalDiv = this.renderConditionalDiv(attributes);
    if (ifRenderConditionalDiv) {
      return (
        <div className="medium-7 conditional-messages">
          {renderExcessShipping(attributes)}

          {renderGiftPackagingMessage(attributes)}

          {attributes.rewards_message && (
            <div className="mojo-tagline-4" data-automation="rewards-message">
              {attributes.rewards_message}
            </div>
          )}

          {attributes.customer_delivery_notes && (
            <div
              className="mojo-tagline-4"
              data-automation="customer-delivery-notes"
            >
              {attributes.customer_delivery_notes}
            </div>
          )}
        </div>
      );
    }
  };
  render() {
    let data = undefined;
    return this.props.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 retailPrice = this.props.showCorrectPrice(
          itemDetails.retail_price
        );
        const priceTimesQuantity = showMultipleSameItemPrice(
          itemDetails.quantity,
          itemDetails.product_price
        );
        const dataId = item[data].id;
        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.state.sizeChanging ||
                  this.state.qtyChanging ||
                  this.state.applying_save_for_later) &&
                this.checkId == dataId
              }
              label="SAVING"
              labelPosition="middle"
            >
              <div
                className="data-container"
                data-item-moved={
                  this.state.itemRemoved && this.checkId == dataId
                }
              >
                {this.renderTimer(itemDetails)}
                {this.renderTSErrorMessage(item[data])}
                {this.renderBtqErrorMessage(item[data])}
                {[
                  itemDetails.errors &&
                    itemDetails.errors.type !==
                      'SHORT_QUANTITY_EXCEEDED_MESSAGE' &&
                    itemDetails.errors.type !== 'SHORT_SIZE_SOLD_OUT_MESSAGE' &&
                    itemDetails.errors.type !== 'SHORT_SOLD_OUT_MESSAGE' &&
                    this.renderErrorMessage(itemDetails)
                ]}
                <a
                  className="container-no-x"
                  href={itemDetails.url}
                  onClick={() =>
                    checkoutProductClicked(itemDetails, 'checkout')
                  }
                >
                  <div className="image-container">
                    <div className="image">
                      <Image
                        desktop={itemDetails.image_medium}
                        mobile={itemDetails.image_medium}
                      />
                    </div>
                  </div>
                </a>
                <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}
                      </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>
                  </div>
                  {itemDetails.customization && (
                    <div
                      className="mojo-tagline-4"
                      data-automation="customization"
                    >
                      <div className="personalization-header">
                        Personalization
                      </div>
                      <div className="personalization-text">
                        {itemDetails.customization}
                      </div>
                    </div>
                  )}
                  {// eslint-disable-next-line no-undef
                  !this.props.isMobile && [
                    this.renderExpectedDeliveryDate(itemDetails)
                  ]}
                  <div className="other-info">
                    <div
                      className={classNames('item-info size', {
                        'size-error': this.showSizeError(itemDetails)
                      })}
                    >
                      <ShippingAddressSelect
                        name="Size"
                        options={itemDetails.size_options.map(size => ({
                          label: size.value,
                          value: size.value,
                          disabled: size.disabled
                        }))}
                        currentOption={{
                          label: itemDetails.size,
                          value: itemDetails.size
                        }}
                        required={false}
                        setCurrentOption={sizeHash =>
                          this.updateQuantitySize(
                            item[data],
                            this.sku_id_for_size(
                              sizeHash.value,
                              itemDetails.size_options
                            ),
                            itemDetails.quantity,
                            'update_size',
                            itemDetails.size
                          )
                        }
                        className={classNames({
                          'size-error': this.showSizeError(itemDetails)
                        })}
                        disabled={this.renderDisabledSize(itemDetails)}
                        reset={false}
                      />
                      {itemDetails.low_stock_alert && (
                        <span
                          className={classNames('light low-stock-alert', {
                            'low-stock-alert--red':
                              this.props.feature_flags &&
                              this.props.feature_flags['red-low-stock-alert']
                          })}
                        >
                          {itemDetails.low_stock_alert}
                        </span>
                      )}
                    </div>
                    <div
                      className={classNames('item-info qty', {
                        'qty-error': this.showQtyError(itemDetails)
                      })}
                    >
                      <ShippingAddressSelect
                        name="qty"
                        // eslint-disable-next-line no-undef
                        options={_.range(
                          0,
                          itemDetails.max_quantity >= 10
                            ? 10
                            : itemDetails.max_quantity
                        ).map(i => ({
                          label: i + 1,
                          value: i + 1
                        }))}
                        reset={false}
                        required={false}
                        setCurrentOption={qtyHash =>
                          this.updateQuantitySize(
                            item[data],
                            itemDetails.sku_id,
                            qtyHash.value,
                            'update_qty',
                            itemDetails.quantity
                          )
                        }
                        currentOption={{
                          label: itemDetails.quantity.toString(),
                          value: itemDetails.quantity.toString()
                        }}
                        className={classNames({
                          'qty-error': this.showQtyError(itemDetails)
                        })}
                        disabled={this.renderDisabledQty(itemDetails)}
                      />
                    </div>
                    {itemDetails.errors &&
                      (itemDetails.errors.type ===
                        'SHORT_QUANTITY_EXCEEDED_MESSAGE' ||
                        itemDetails.errors.type ===
                          'SHORT_SIZE_SOLD_OUT_MESSAGE') &&
                      this.renderErrorMessage(itemDetails)}
                  </div>
                  {// eslint-disable-next-line no-undef
                  !this.props.isMobile && [
                    this.renderReturnPolicy(itemDetails),
                    this.renderReserveToday(itemDetails)
                  ]}
                  {// eslint-disable-next-line no-undef
                  this.props.isMobile && [
                    this.renderExpectedDeliveryDate(itemDetails),
                    this.renderReturnPolicy(itemDetails),
                    this.renderReserveToday(itemDetails)
                  ]}
                </div>
                {this.renderConditionalMessages(itemDetails)}
                <div className="medium-7 checkout-product-remove-v2">
                  <div className="column mojo-panel_controls-v2 mojo-panel_controls--bottom bottom-button-links-v2">
                    <span
                      className="mojo-tagline-button padding-top-15--medium padding-top-15--small save-for-later-remove"
                      onClick={() => {
                        this.saveForLater(item[data].id);
                      }}
                      data-automation="save-for-later"
                    >
                      Save for later
                    </span>
                    <span className="mojo-panel_controls_divider">|</span>
                    <span
                      className="mojo-tagline-button padding-top-15--medium padding-top-15--small save-for-later-remove"
                      onClick={() => {
                        this.handleRemoveItem(
                          dataId,
                          itemDetails.quantity,
                          itemDetails
                        );
                      }}
                      data-automation="remove-save-for-later"
                    >
                      Remove
                    </span>
                  </div>
                </div>
              </div>
            </LoadingOverlay>
          </div>
        );
      }
    });
  }
}

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

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

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