import * as React from 'react';
import { Utils } from '@assets/js-shop/cart/Utils';
import { DataContext } from '@assets/js-shop/context';
import { IShopDataContext } from '@assets/js-shop/Interfaces';
import { translate as _t } from '@assets/js-shop/ShopUtils';
import FreeShipping from '@assets/js-shop/cart/footer/FreeShipping';
import config from '@assets/js-shop/config';
import { CartboxFooterBenefits } from '@assets/js-shop/cart/footer/CartboxFooterBenefits';

interface CartboxFooterProps {
   toggleCartVisibility(): void;
   loading: boolean;
}

interface BenefitsProps {
   context: IShopDataContext;
}

export class CartboxFooter extends React.PureComponent<CartboxFooterProps> {
   state = {
      isSubmitting: false,
   };

   static contextType = DataContext;
   context: React.ContextType<typeof DataContext>;

   componentDidMount() {
      window.addEventListener('pageshow', this.pageShowListener);
   }
   componentWillUnmount() {
      window.removeEventListener('pageshow', this.pageShowListener);
   }

   pageShowListener = (event: PageTransitionEvent) => {
      // When page is loaded from bf cache, set isSubmitting to false. Otherwise, "isSubmitting" will be true after user returns from cart via navigation buttons
      if (event.persisted && this.state.isSubmitting) {
         this.setState({ isSubmitting: false });
      }
   };

   handleClick = () => {
      this.setState({ isSubmitting: true });
   };

   render() {
      const context: IShopDataContext = this.context;
      const loading = this.props.loading;
      const { isSubmitting } = this.state;

      return (
         <div className="cartbox-footer">
            <div className="price-title">
               <span className="title">{_t('mezisoucet')}</span>
               <strong className="total-price h3">
                  {Utils.printPrice(context.cart.totalPrice, context)}
               </strong>
               <div>
                  {config.moduleTotalCharges && (context.cart?.charges?.withVat ?? 0) >= 1 ? (
                     <span className="cart-charges">
                        {_t('charges')} {Utils.printPrice(context.cart.charges, context)}
                     </span>
                  ) : (
                     ''
                  )}
                  {config.moduleTotalSavings && context.cart.savings.withVat >= 1 ? (
                     <span className="cart-saving">
                        {_t('savings')} {Utils.printPrice(context.cart.savings, context)}
                     </span>
                  ) : (
                     ''
                  )}
               </div>
            </div>

            <div className="cartbox-shipping-progress-wrapper">
               {context.me?.isB2B && config.B2BHiddenFreeShipping ? (
                  ''
               ) : (
                  <>
                     {context.cart.freeDeliveryFrom > 0 && (
                        <FreeShipping
                           freeDeliveryFrom={context.cart.freeDeliveryFrom}
                           totalPrice={context.cart.totalPrice.withVat}
                           isFreeShipping={context.cart?.shippingInfo?.isFreeShipping}
                        />
                     )}
                  </>
               )}

               {context.me?.isB2B && config.B2BHiddenFooterBenefits ? (
                  ''
               ) : (
                  <CartboxFooterBenefits />
               )}
            </div>

            {(context.cart.items.length > 0 || context.me?.isB2B) && (
               <a
                  href={context.cart.url}
                  className={`btn btn-block btn-primary ${loading ? 'disabled' : ''} ${isSubmitting ? 'is-submitting' : ''}`}
                  onClick={this.handleClick}>
                  {_t('prejitDoKosiku')}
               </a>
            )}
            <a
               className="back"
               onClick={this.props.toggleCartVisibility}
               onKeyDown={(e) => {
                  if (e.key === 'Enter') this.props.toggleCartVisibility();
               }}
               role="button"
               tabIndex={0}>
               {MODULES.COMPONENTS ? (
                  <i
                     className="c-icon"
                     dangerouslySetInnerHTML={{
                        __html: require('@assets/icons/icons_caret-left.svg?raw'),
                     }}
                  />
               ) : (
                  ''
               )}
               {_t('zpetKNakupu')}
            </a>
         </div>
      );
   }
}
