import React, {PureComponent} from 'react';
import {withRouter} from 'react-router';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import get from 'lodash.get';
import ShoppingBagIcon from '@moda/icons/shopping-bag-24';
import MiniCartContainer from './mini_cart_container';
import MiniCartJustAdded from './mini_cart_just_added';
import MiniCartJustAddedSmall from './mini_cart_just_added_small';
import {getIsTouchDevice, getViewType} from './../../shared/utils/site_utils';
import {
  miniCartIconClicked,
  miniCartIconHovered
} from '../utils/event_tracking';
import './mini_cart_icon.scss';

export class MiniCartIcon extends PureComponent {
  static propTypes = {
    addToCart: PropTypes.func,
    carts: PropTypes.object,
    boxShown: PropTypes.bool,
    resetBoxShow: PropTypes.func,
    location: PropTypes.object,
    feature_flags: PropTypes.object,
    current_user_present: PropTypes.bool,
    proceedToCheckout: PropTypes.func,
    proceedToCheckoutAsGuest: PropTypes.func,
    showLoadingOverlay: PropTypes.func,
    disable_deposit_msg: PropTypes.bool,
    updateCartEntity: PropTypes.func,
    atcRecommendationsOn: PropTypes.bool,
    vertical: PropTypes.string
  };

  constructor(props) {
    super(props);
    this.state = {
      miniCartOpen: false,
      cartItemsCount: get(this.props.carts, 'attributes.cart_items_count'),
      boxShownState: this.props.boxShown,
      showMarkdownNotification: false,
      hasUserSeenNotification: false,
      markdownNotificationLoaded: false,
      recommendationsRef: null
    };
  }
  refAddToCartRecs = React.createRef();
  autoCloseMiniCartJustAdded = nextProps => {
    setTimeout(
      () => {
        this.setState({
          boxShownState: nextProps.boxShown
        });
      },
      getIsTouchDevice() ? 2000 : 4000
    );
  };

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.boxShown != nextProps.boxShown && !this.state.miniCartOpen)
      if (nextProps.boxShown) {
        // Show item added immediately but hide after 7 seconds (3 seconds from mojo actions + 4)
        this.setState({
          boxShownState: nextProps.boxShown
        });
      } else {
        if (!this.props.atcRecommendationsOn) {
          this.autoCloseMiniCartJustAdded(nextProps);
        }
      }
    if (
      (this.props.location && this.props.location.pathname) !==
      (nextProps.location && nextProps.location.pathname)
    ) {
      // If we moved to a new page with different url - close mini cart
      this.resetBoxShown();
      this.handleIsNotHovered();
    }
  }

  componentDidUpdate() {
    const {carts} = this.props;
    if (carts && carts.attributes && carts.attributes.cart_items_count == 0)
      setTimeout(() => {
        this.setState({
          miniCartOpen: false
        });
      }, 2000);
    if (
      !this.state.markdownNotificationLoaded &&
      carts &&
      carts.attributes &&
      carts.attributes.markdown_notification !== undefined
    ) {
      this.setState({
        showMarkdownNotification: carts.attributes.markdown_notification,
        markdownNotificationLoaded: true
      });
    }
  }

  resetBoxShown = () => {
    this.setState({boxShownState: false});
  };

  markdownNotificationSeen = () => {
    this.setState({
      hasUserSeenNotification: true
    });
    this.updateMarkdownNotificationSeen();
  };

  updateMarkdownNotificationSeen = () => {
    const {carts} = this.props;
    const attributes = {
      markdown_notification: false
    };
    this.props.updateCartEntity(
      {
        type: 'carts',
        id: carts.id,
        action_type: 'markdown_notification',
        attributes: attributes
      },
      {
        section: 'markdown_notification'
      }
    );
  };

  handleIsHovered = () => {
    this.setState({
      miniCartOpen: true
    });
    setTimeout(() => {
      if (this.state.miniCartOpen) {
        miniCartIconHovered();
        if (this.state.showMarkdownNotification) {
          this.markdownNotificationSeen();
        }
      }
    }, 3000);
  };

  handleIsNotHovered = () => {
    this.setState({
      miniCartOpen: false
    });
    if (
      this.state.showMarkdownNotification &&
      this.state.hasUserSeenNotification
    ) {
      this.setState({
        showMarkdownNotification: false
      });
    }
  };

  showCorrectPrice = price => {
    return `${price.currency_html_code}${price.human}`;
  };

  getTrunkshowDepositRate() {
    const trunkshow_deposit_rate =
      typeof isFeatureFlagEnabled !== 'undefined' &&
      // eslint-disable-next-line no-undef
      isFeatureFlagEnabled('variable-deposit-new')
        ? 0.25
        : 0.5;
    return trunkshow_deposit_rate;
  }

  getLastItemAdded = (orderItems, lastItemId) => {
    const lastItem = orderItems.filter(
      item => get(item, 'data.id', null) == lastItemId
    );
    return (
      lastItem &&
      lastItem.length != 0 &&
      get(lastItem[0], 'data.attributes', null)
    );
  };

  renderMiniCartJustAdded() {
    const viewTypeMobile = getViewType() === 'mobile';
    const {carts} = this.props;
    const orderItems = carts.attributes.order_items;
    const lastItemId = carts.attributes.last_item_id;
    const lastItemAdded = this.getLastItemAdded(orderItems, lastItemId);
    if (this.props.atcRecommendationsOn && viewTypeMobile) {
      return (
        <MiniCartJustAddedSmall
          showModal={this.state.boxShownState}
          reset={this.resetBoxShown}
          showCorrectPrice={this.showCorrectPrice}
          cart={carts}
          feature_flags={this.props.feature_flags}
          lastItemId={lastItemId}
          orderItems={orderItems}
          current_user_present={this.props.current_user_present}
          proceedToCheckout={this.props.proceedToCheckout}
          proceedToCheckoutAsGuest={this.props.proceedToCheckoutAsGuest}
          disableDepositMessage={this.props.disable_deposit_msg}
          trunkshow_deposit_rate={this.getTrunkshowDepositRate()}
          recommendationsRef={this.refAddToCartRecs}
          lastItemAdded={lastItemAdded}
          handleAddToCart={this.props.addToCart}
          vertical={this.props.vertical}
        />
      );
    } else
      return (
        <MiniCartJustAdded
          reset={this.resetBoxShown}
          showCorrectPrice={this.showCorrectPrice}
          cart={carts}
          feature_flags={this.props.feature_flags}
          lastItemId={lastItemId}
          orderItems={orderItems}
          current_user_present={this.props.current_user_present}
          proceedToCheckout={this.props.proceedToCheckout}
          proceedToCheckoutAsGuest={this.props.proceedToCheckoutAsGuest}
          disableDepositMessage={this.props.disable_deposit_msg}
          trunkshow_deposit_rate={this.getTrunkshowDepositRate()}
          lastItemAdded={lastItemAdded}
        />
      );
  }

  render() {
    const {location, carts} = this.props;
    const isTouchDevice = getIsTouchDevice();
    const inShoppingBagOrCheckout =
      typeof location !== 'undefined' &&
      (!!location.pathname.match(/^\/shopping-bag/) ||
        !!location.pathname.match(/^\/checkout/));
    const cartItemCount = get(carts, 'attributes.cart_items_count', null);

    return (
      <>
        <div
          onMouseEnter={
            !isTouchDevice && !inShoppingBagOrCheckout
              ? this.handleIsHovered
              : null
          }
          onMouseLeave={
            !isTouchDevice && !inShoppingBagOrCheckout
              ? this.handleIsNotHovered
              : null
          }
          className={classNames('shopping-bag-component', {
            'in-shopping-bag': inShoppingBagOrCheckout
          })}
        >
          <a
            className={classNames(
              'mo-web-link mo-web-link--gold mo-web-shopping-bag ga-track-link',
              {
                'in-shopping-bag': inShoppingBagOrCheckout
              }
            )}
            href="/shopping-bag"
            theme="gold"
            title="Shopping Bag"
            data-link-actions="click"
            data-link-category="NAVIGATION"
            data-link-label="SHOPPING BAG"
            data-link-value="0"
            data-automation="shopping-bag-icon"
            onClick={() => miniCartIconClicked()}
          >
            <div className="mo-web-shopping-bag__icon">
              <div
                className={classNames({
                  'markdown-notification':
                    this.props.feature_flags['bag-markdown-notification'] &&
                    this.state.showMarkdownNotification
                })}
              >
                <ShoppingBagIcon />
              </div>
            </div>
            {Boolean(cartItemCount) && `(${cartItemCount})`}
          </a>
          {this.state.miniCartOpen &&
            !this.state.boxShownState &&
            !isTouchDevice && (
              <MiniCartContainer
                miniCartOpen={this.state.miniCartOpen}
                cart={get(carts, 'attributes', null)}
                showCorrectPrice={this.showCorrectPrice}
                feature_flags={this.props.feature_flags}
                current_user_present={this.props.current_user_present}
                proceedToCheckout={this.props.proceedToCheckout}
                proceedToCheckoutAsGuest={this.props.proceedToCheckoutAsGuest}
                showLoadingOverlay={this.props.showLoadingOverlay}
                disableDepositMessage={this.props.disable_deposit_msg}
                trunkshow_deposit_rate={this.getTrunkshowDepositRate()}
                showMarkdownNotification={this.state.showMarkdownNotification}
              />
            )}
          {carts && this.state.boxShownState && this.renderMiniCartJustAdded()}
        </div>
      </>
    );
  }
}

export default withRouter(MiniCartIcon);
