import {updateEeaProducts, updateEeaCheckoutProducts, syncEeaProducts} from './basket/gtm';
import {
    toggleWisdom,
    checkDeliveryStock,
    addDeliveryStock,
    createWisdom,
    changeWisdomWhenQuantityUpdated,
    checkDeliveryStockOnEnter,
    prettifyWisdomPostcode
} from './basket/wisdom';
import {updateOrderSummary} from './components/order-summary';
import {checkVoucherCode, voucherRemove} from './components/voucher';
import {updateKlarnaPlacements} from './basket/klarna';
import {checkPayPalAvailability} from './basket/paypal';
import {
    updateCharity,
    changeCharityPrice,
    toggleCharityElements,
    setDefaultCharityValue
} from './components/charity';
import {callAction} from './utils/http-action';
import {ROUTES} from './utils/routes';
import {
    getUniqBasketSessionId,
    updateBasketSession,
    addStorageCheckEvent,
    updateBasketDataQuantity,
} from './basket/session-sync'
import {displayEnergyEfficiency} from "./basket/display-energy-efficiency";
import {appendLoader, hideLoader} from "./utils/loader";

var Wick = window.Wick || {};
Wick.BasketPage = {
    el: {
        $voucherFormBtn: $('.voucher__btn'),
        value: '.checkout-widget__item-value',
        discountValue: '.checkout-widget__detail-value',
        $orderTotal: $('.checkout-widget__total'),
        orderTotalValue: '.checkout-widget__total-value',
        $orderItem: $('.order-item'),
        content: '.content',
        orderItem: '.order-item',
        total: '.order-item__total',
        promo: '.p-promotion',
        promoClose: '.p-promotion__close',
        quantityButton: '.order-item__quantity-btn',
        removeButton: '.order-item__remove',
        quantityValue: '.order-item__quantity-value',
        ccSection: '.cc-order',
        ccOrderInfo: '.cc-order__info',
        ccOrderInfoHide: 'cc-order__info-hide',
        storeUnselected: '.cc-order__store-unselected',
        ccCloseLink: '.cc-order__close-link',
        ccButton: '.order-item__action[data-type="Click & Collect"]',
        deliveryButtonInCC: '.order-item__action[data-type="Delivery"]',
        deliveryStockButton: '.order-item__action[data-type="Delivery Stock"]',
        totalHide: 'order-item__total-hide',
        btnSelected: 'order-item__action-selected',
        btnSecondary: 'btn-secondary',
        basketMainSection: '.basket__section',
        actionButton: '.order-item__action',
        deliveryMessage: '.order-item__delivery',
        basketDeliverySection: '.basket__section[data-type="Delivery"]',
        basketCCSection: '.basket__section[data-type="Click & Collect"]',
        updateStoreButton: 'button[id^="update_store"]',
        orderSectionCta: '.cc-order__section-cta',
        itemTotal: '.order-item__total-value .order-item__value',
        orderItemValue: '.order-item__value',
        orderItemValueSm: 'order-item__value-sm',
        orderItemValueXs: 'order-item__value-xs',
        discountItem: '.checkout-widget__details-discount',
        orderItemInfo: '.order-item__info',
        orderItemInfoTile: 'order-item__info-tile',
        orderItemOffers: '.order-item__offers',
        orderItemInfoOffers: 'order-item__info-offers',
        charityInput: '#donation',
        charityItem: '.charity-new',
        donationCartBtn: '.donation-cart__btn',
        checkoutWidgetDetails: '.checkout-widget__details',
        checkoutWidgetDetailsFlex: 'checkout-widget__details-flex',
        subtotal: '.checkout-widget__item-bold',
        vat: '.checkout-widget__item-vat',
        delivery: '.checkout-widget__item-delivery',
        charity: '.checkout-widget__item-charity',
        cc: '.checkout-widget__item-cc',
        orderTotal: '.checkout-widget__total',
        orderSummary: '.checkout-widget_order-summary',
        voucherRemove: '.checkout-widget__voucher-remove',
        promoWrapper: '.checkout-header__promo',
        wisdomClose: '.order-item__wisdom-link',
        wisdomCheck: '.wisdom__btn-check',
        wisdomAdd: '.wisdom__btn-add',
        wisdomBlock: '.order-item__wisdom',
        wisdomBlockHide: 'order-item__wisdom-hide',
        changeLink: '.wisdom__link',
        checkoutHeader: '.checkout-header',
        summaryAccordion: '.summary__accordion',
        summaryLarge: '.summary-large',
        summaryAccordionText: '.summary__accordion-text',
        storeName: '.store__name',
        storeNameText: '.store__name-text',
        titleItems: '.checkout-title__items',
        wisdomPostcode: '.wisdom-postcode',
        orderItemQuantityControl: '.order-item__quantity-control',
        orderItemQuantityControlDisabledClass: 'order-item__quantity-control-disabled',
        loader: '.basket-loader'
    },
    cartEntries: [],
    sessionId: getUniqBasketSessionId(),
    loaderPayload: {
        wrapper: 'body',
        hidden: true,
        titleLoader: "Updating basket…",
        modifier: "basket-loader"
    },
    getEqualMapForUpdateCart: function (data) {
        return [
            {
                item: Wick.BasketPage.el.subtotal,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.subtotalWithoutCharity.formattedValue,
                value: data.subTotal.value,
                title: 'Items subtotal:'
            },
            {
                item: Wick.BasketPage.el.vat,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.totalTax.formattedValue,
                value: data.totalTax.value,
                title: 'VAT:'
            },
            {
                item: Wick.BasketPage.el.cc,
                itemValue: Wick.BasketPage.el.value,
                dataValue: 'Free',
                title: 'Click & Collect:'
            },
            {
                item: Wick.BasketPage.el.delivery,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.deliveryCost.formattedValue,
                value: data.deliveryCost.value,
                title: 'Delivery:'
            },
            {
                item: Wick.BasketPage.el.charity,
                itemValue: Wick.BasketPage.el.value,
                dataValue: data.charityPrice.formattedValue,
                value: data.charityPrice.value,
                title: 'Charity donation:'
            },
            {
                item: Wick.BasketPage.el.discountItem,
                itemValue: Wick.BasketPage.el.discountValue,
                dataValue: data.totalDiscounts ? data.totalDiscounts.formattedValue : '',
                value: data.totalDiscounts ? data.totalDiscounts.value : '',
            },
            {
                item: Wick.BasketPage.el.orderTotal,
                itemValue: Wick.BasketPage.el.orderTotalValue,
                dataValue: data.totalPrice.formattedValue,
                value: data.totalPrice.value,
            },
        ];
    },
    updateItemQuantity: function (e) {
        let context,
            charity,
            $currentItem = $(e.currentTarget).closest(Wick.BasketPage.el.orderItem),
            $otherItems = $(Wick.BasketPage.el.orderItem).not($currentItem);

        Wick.BasketPage.addQuantityDisable($otherItems);

        if ($(this).closest(Wick.BasketPage.el.orderItem).length) {
            context = $(this).closest(Wick.BasketPage.el.orderItem);
        } else if ($(this).closest(Wick.BasketPage.el.charityItem).length) {
            charity = true;
            context = $(this).closest(Wick.BasketPage.el.charityItem);
        }

        let quantityInput = context.find(Wick.BasketPage.el.quantityValue),
            value = quantityInput.val(),
            action = $(this).attr('data-action'),
            entryNumber = charity
                ? context.find('input[name="entryNumber"]').val()
                : +context.attr('data-id');

        //for local update quantity value before API Call
        switch (action) {
            case 'plus':
                value = Number.parseInt(value, 10) + 1;
                if (value) {
                    Wick.BasketPage.updateQuantity(quantityInput, value);
                    Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                }
                break;
            case 'minus':
                value = Number.parseInt(value, 10) - 1;
                if (value > 0) {
                    Wick.BasketPage.updateQuantity(quantityInput, value);
                    Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                } else {
                    Wick.BasketPage.removeQuantityDisable();
                }

                break;
            case 'remove':
                value = 0;
                charity || Wick.BasketPage.updateQuantity(quantityInput, value);
                Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                break;
            default:
                if (+value !== 0) {
                    Wick.BasketPage.updateQuantity(quantityInput, value);
                    Wick.BasketPage.debounceQuantityChange(entryNumber, value, quantityInput, context);
                }
                break;
        }

        changeWisdomWhenQuantityUpdated(e, context);
        Wick.BasketPage.toggleItemTotal(context, +quantityInput.val())
    },
    debounceQuantityChange: _.debounce(function (entryNumber, value, quantityInput, context) {
        Wick.BasketPage.updateQuantityAction(entryNumber, value, quantityInput, context)
    }, 500),
    updateQuantityAction: function (entryNumber, quantityToUpdate, quantityInput, context) {
        console.log('case(api) to update quantity', entryNumber, quantityToUpdate);
        //checkEnv
        if (!Wick.checkLocalEnv) {
            // api
            Wick.BasketPage.addQuantityDisable(context);
            const payload = {
                url: `${ROUTES.BASKET_ADD_STOCK}/${entryNumber}`,
                queries: {
                    quantity: quantityToUpdate,
                },
                type: 'PUT',
                complete: Wick.BasketPage.removeQuantityDisable,
            }

            callAction(
              payload,
              Wick.BasketPage.updateAction,
              quantityToUpdate,
              quantityInput,
              context,
              (response) => {
                  if (response.statusMessage === 'accConfirmedMsgs') {
                      const basketSection = Wick.BasketPage.el.basketMainSection;
                      $(document).trigger("EEUpdateCart", {
                          cartEntryNumber: entryNumber,
                          initialCartQuantity: response.quantity - response.quantityAdded,
                          newCartQuantity: response.quantity,
                          fulfillment: context.hasClass('charity-new') ? 'Delivery' : context.closest(basketSection).attr('data-type'),
                      });
                  }
                  context.find(Wick.BasketPage.el.actionButton).removeClass('disabled');
              });
        } else {
            Wick.BasketPage.updateQuantityOperation(
                quantityToUpdate,
                quantityInput,
                context,
                Wick.BasketData.updateQuantity
            );
        }
    },
    updateAction: function (response, quantityToUpdate, quantityInput, context, successCallback) {
        Wick.BasketPage.updateQuantityOperation(
          quantityToUpdate,
          quantityInput,
          context,
          response
        );
        successCallback(response);
    },
    updateQuantityOperation: function (quantityToUpdate, quantityInput, context, data) {
        const charity = context.hasClass('charity-new'),
            negativeStatus = data.statusMessage !== 'accConfirmedMsgs',
            messageInfo = Wick.BasketPage.isMessageExist(data) && Wick.BasketPage.getMessageInfo(data);
        let maxValue, minValue;

        if (!charity) {
            maxValue = +quantityInput.attr('max');
            minValue = +quantityInput.attr('min');
        }

        console.log('errorStatus:', negativeStatus);

        minValue === 0 ? minValue = 1 : minValue = minValue;

        if (negativeStatus) {
            Wick.BasketPage.updateCart(messageInfo);
            Wick.BasketPage.updateQuantity(quantityInput, data.quantity);
            Wick.BasketPage.showNotification(data);
        } else {
            if (charity) {
                Wick.BasketPage.updateCart();
                quantityToUpdate === 0 && toggleCharityElements();
            } else {
                if (maxValue > 1 || minValue > 1) {
                    if (quantityToUpdate > maxValue || quantityToUpdate < minValue) {
                        Wick.BasketPage.showNotification(data);
                    }
                }

                if (quantityToUpdate === 0) {
                    Wick.BasketPage.showNotification(data);
                    Wick.BasketPage.updateCart(messageInfo);
                } else {
                    Wick.BasketPage.updateItemTotal(data, context)
                    Wick.BasketPage.updateCart(null, context)
                }
            }
        }

    },
    isMessageExist: function (data) {
        return data.message && data.statusMessage;
    },
    getMessageInfo: function (data) {
        return {
            message: data.message,
            status: data.statusMessage,
        }
    },
    loadIndexing: function () {
        Wick.BasketPage.el.$orderItem.each(function (index) {
            $(this).attr('data-id', index);
        })
    },
    updateQuantity: function (quantityInput, accum) {
        quantityInput.val(accum);
        quantityInput.attr('value', accum);
    },
    updateItemTotal: function (data, context) {
        if (Number.isFinite(data.entry?.entryNumber)) {
            let totalValue = context.find(Wick.BasketPage.el.itemTotal);
            let totalPrice = data.entry.itemTotalWithoutDiscount.formattedValue;
            totalValue.text(totalPrice);
        }
    },
    toggleItemTotal: function (context, quantity) {
        quantity <= 1
            ? $(context).find(Wick.BasketPage.el.total).addClass(Wick.BasketPage.el.totalHide)
            : $(context).find(Wick.BasketPage.el.total).removeClass(Wick.BasketPage.el.totalHide);
    },
    updateCart: function (repaintData, context, charity, initial, callback) {
        console.log('case(api) to update cart');
        const info = {repaintData, context, charity, initial}
        const actionCallback = callback || Wick.BasketPage.updateCartAction;

        if (!Wick.checkLocalEnv) {
            const payload = {
                url: ROUTES.BASKET_GET_CART,
                type: 'GET',
                complete: hideLoader(Wick.BasketPage.el.loader),
            }

            callAction(payload, actionCallback, info)
        } else {
            if (initial) {
                Wick.BasketPage.getCartEntries(Wick.BasketData.updateCart);
            } else {
                updateBasketDataQuantity();
                updateOrderSummary(
                    Wick.BasketData.updateCart,
                    Wick.BasketPage.getEqualMapForUpdateCart(Wick.BasketData.updateCart)
                );

                !repaintData || Wick.BasketPage.repaintOrderItems(Wick.BasketData.updateCart, repaintData);
                !charity || Wick.BasketPage.addCharityEntryNumber(Wick.BasketData.updateCart);

                //update promotion when update quantity
                if (context && context.length) {
                    Wick.BasketPage.updatePromotion(Wick.BasketData.updateCart, context);
                }

                updateKlarnaPlacements(Wick.BasketData.updateCart.totalPrice.formattedPriceWithoutCurrencySymbol);

                Wick.BasketPage.addPotentialPromo(Wick.BasketData.updateCart);
                Wick.BasketPage.getCartEntries(Wick.BasketData.updateCart);
                Wick.BasketPage.checkProductArrays(Wick.BasketData.updateCart) || Wick.BasketPage.removeOrderItem(repaintData);
                updateBasketSession();
                Wick.EnergyEfficiency && Wick.EnergyEfficiency.drawEnergyLabels();
                setTimeout(hideLoader, 1000);
            }
        }
    },
    updateCartAction: function (response, info) {
        if (info.initial) {
            Wick.BasketPage.getCartEntries(response);
        } else {
            updateOrderSummary(response, Wick.BasketPage.getEqualMapForUpdateCart(response));
            if (info.repaintData) {
                if (info.repaintData.isChangeDelivery) {
                    info.repaintData.cartEntry = Wick.BasketPage.cartEntries
                        .filter(entry => entry.entryNumber === info.repaintData.cartEntryNumber)[0];
                    $(document).trigger("EEUpdateDeliveryMode", info.repaintData);
                }

                Wick.BasketPage.checkProductArrays(response) ?
                    Wick.BasketPage.repaintOrderItems(response, info.repaintData) :
                    (() => {
                        $(Wick.BasketPage.el.orderItem).remove();
                        Wick.BasketPage.removeOrderItem(info.repaintData);
                    })();
            }

            !info.charity || Wick.BasketPage.addCharityEntryNumber(response);

            //update promotion when update quantity
            if (info.context && info.context.length) {
                Wick.BasketPage.updatePromotion(response, info.context);
            }

            Wick.BasketPage.addPotentialPromo(response);
            updateEeaProducts(response.deliveryOrderGroups, response.pickupOrderGroups);
            updateEeaCheckoutProducts(response.deliveryOrderGroups, response.pickupOrderGroups);
            syncEeaProducts();
            $(document).trigger("cartUpdate");
            Wick.BasketPage.getCartEntries(response);
            updateKlarnaPlacements(response.totalPrice.formattedPriceWithoutCurrencySymbol);
            updateBasketSession();
            Wick.EnergyEfficiency.drawEnergyLabels()
        }
    },
    checkProductArrays(cart) {
        return cart.pickupUniqueItemsNumber || cart.deliveryUniqueItemsNumber;
    },
    getCartEntries(data) {
        Wick.BasketPage.cartEntries = data.deliveryOrderGroups.concat(data.pickupOrderGroups)
            .map(orderGroup => orderGroup.entries)
            .flatMap(entries => entries);
    },
    addCharityEntryNumber: function (data) {
        let entryNumber;
        data.deliveryOrderGroups.forEach(order => {
            order.entries.forEach(item => {
                item.charity ? entryNumber = item.entryNumber : null
            })
        })
        if ($(Wick.BasketPage.el.charityItem).find('input[name="entryNumber"]').length) {
            $(Wick.BasketPage.el.charityItem).find('input[name="entryNumber"]').val(entryNumber)
        } else {
            $(Wick.BasketPage.el.charityItem).prepend(
                `<input type="hidden" name="entryNumber" value="${entryNumber}">`
            )
        }
    },
    updatePromotion: function (data) {
        $(Wick.BasketPage.el.orderItem).each(function () {
            let itemNumber = {entryNumber: +$(this).attr('data-id')}
            $(this).find(Wick.BasketPage.el.orderItemOffers).remove()
            $(this).find(Wick.BasketPage.el.orderItemInfo).append(Wick.BasketPage.addPromotions(itemNumber, data));
        })
    },
    showNotification: function (data) {
        let notificationType;
        switch (data.statusMessage) {
            case 'accConfirmedMsgs':
                notificationType = 'success'
                break;
            case 'accWarnMsgs':
                notificationType = 'warning'
                break;
            case 'accErrorMsgs':
                notificationType = 'error'
                break;
        }

        Wick.Notification.show({
            text: data.message,
            container: '.notification-area',
            type: notificationType,
            closeBtn: true
        });

    },
    hideUnusedDeliveryTypeCost: function (data, isVoucher) {
        $(Wick.BasketPage.el.delivery).show()
        $(Wick.BasketPage.el.cc).show()
        if (isVoucher) {
            if (!data.deliveryOrder) {
                $(Wick.BasketPage.el.delivery).hide()
            } else if (!data.clickAndCollectOrder) {
                $(Wick.BasketPage.el.cc).hide()
            }
        } else {
            if (data.clickAndCollectOnly) {
                $(Wick.BasketPage.el.delivery).hide()
            } else if (data.deliveryItemsQuantity > 0 && data.pickupItemsQuantity === 0) {
                $(Wick.BasketPage.el.cc).hide()
            }
        }
    },
    paintActionButton: function () {
        $(Wick.BasketPage.el.basketMainSection).each(function () {
            if ($(this).attr('data-type') === "Delivery") {
                $(this).find(Wick.BasketPage.el.actionButton).each(function () {
                    $(this).removeClass(Wick.BasketPage.el.btnSelected);
                    if ($(this).attr('data-type') === "Delivery" || $(this).attr('data-type') === "Delivery Stock") {
                        $(this).addClass(Wick.BasketPage.el.btnSelected);
                        $(this).find('input').prop('checked', true);
                    }
                })
            } else if ($(this).attr('data-type') === "Click & Collect") {
                $(this).find(Wick.BasketPage.el.actionButton).each(function () {
                    $(this).removeClass(Wick.BasketPage.el.btnSelected);
                    if ($(this).attr('data-type') === "Click & Collect") {
                        $(this).addClass(Wick.BasketPage.el.btnSelected);
                        $(this).find('input').prop('checked', true);
                    }
                })
            }
        })
    },
    hideCCSectionInDelivery: function (context) {
        let delivery = context.find(Wick.BasketPage.el.deliveryMessage),
            cc = context.find(Wick.BasketPage.el.ccSection);

        delivery.show();
        cc.hide();
    },
    showCCSectionInDelivery: function (e) {
        e.preventDefault();
        if ($(this).closest(Wick.BasketPage.el.basketDeliverySection).length) {
            Wick.BasketPage.makeRadioActive(this);
            let context = $(this).closest(Wick.BasketPage.el.orderItem),
                delivery = context.find(Wick.BasketPage.el.deliveryMessage),
                cc = context.find(Wick.BasketPage.el.ccSection),
                wisdom = context.find(Wick.BasketPage.el.wisdomBlock),
                ccOrderInfo = context.find(Wick.BasketPage.el.ccOrderInfo);

            delivery.hide();
            cc.show();
            ccOrderInfo.removeClass(Wick.BasketPage.el.ccOrderInfoHide);

            //hide wisdom if exist
            wisdom.length && wisdom.addClass(Wick.BasketPage.el.wisdomBlockHide)

            context.find(Wick.BasketPage.el.storeUnselected).unbind();
            context.find(Wick.BasketPage.el.ccCloseLink).unbind();

            context.find(Wick.BasketPage.el.storeUnselected).on('click', (e) => e.preventDefault());
            context.find(Wick.BasketPage.el.ccCloseLink).on('click', function (e) {
                e.preventDefault();
                Wick.BasketPage.makeRadioActive(context.find(Wick.BasketPage.el.deliveryButtonInCC));
                Wick.BasketPage.hideCCSectionInDelivery(context);
            })
        } else {
            Wick.BasketPage.makeRadioActive(this);
            $(this).closest(Wick.BasketPage.el.orderItem).find(Wick.BasketPage.el.wisdomClose).trigger('click');
        }
    },
    changeMethodToDelivery: function (e) {
        e.preventDefault();

        if ($(this).closest(Wick.BasketPage.el.basketCCSection).length) {
            Wick.BasketPage.makeRadioActive(this);

            let context = $(this).closest(Wick.BasketPage.el.orderItem),
                entryNumber = +context.attr('data-id');
            console.log('case(api) change to delivery method, entry =', entryNumber);

            const options = {
                cartEntryNumber: entryNumber,
                cartEntry: {},
                fulfilmentData: {
                    fulfillmentType: 'Delivery'
                },
                isChangeDelivery: true,
            }

            //checkEnv
            if (!Wick.checkLocalEnv) {
                // api
                const payload = {
                    url: `${ROUTES.BASKET_ADD_STOCK}/${entryNumber}/delivery`,
                    type: 'PUT',
                }
                callAction(payload, Wick.BasketPage.updateDeliveryMethod, options)
            } else {
                Wick.BasketPage.showNotification(Wick.BasketData.changeMethod)
                Wick.BasketPage.updateCart(options);
            }
        } else {
            Wick.BasketPage.makeRadioActive(this);
            Wick.BasketPage.hideCCSectionInDelivery($(this).closest(Wick.BasketPage.el.orderItem));
        }
    },
    changeMethodToCC: function () {
        let context = $(this).closest(Wick.BasketPage.el.orderItem),
            storeId = $(this).closest(Wick.BasketPage.el.orderSectionCta).find('.storeNamePost').val(),
            entryNumber = +context.attr('data-id'),
            quantity = context.find(Wick.BasketPage.el.quantityValue).val(),
            storeName;

        context.find(Wick.BasketPage.el.storeName).each((i, el) => {
            if ($(el).find('input').attr('value') === storeId) {
                storeName = $(el).find(Wick.BasketPage.el.storeNameText).text().trim();
            }
        })

        console.log('case(api) change to C&C method, entry -', entryNumber, 'storeId', storeId, 'qty-', quantity, 'storeName-', storeName);

        const options = {
            cartEntryNumber: entryNumber,
            cartEntry: {},
            fulfilmentData: {
                fulfillmentType: 'C&C',
                storeId: storeId,
                storeName: storeName,
            },
            isChangeDelivery: true,
        }

        //checkEnv
        if (!Wick.checkLocalEnv) {
            // api
            const payload = {
                url: `${ROUTES.BASKET_ADD_STOCK}/${entryNumber}/collection`,
                queries: {
                    storeId: storeId,
                    quantity: quantity,
                },
                type: 'PUT',
            }
            callAction(payload, Wick.BasketPage.updateDeliveryMethod, options)
        } else {
            Wick.BasketPage.showNotification(Wick.BasketData.changeMethod)
            Wick.BasketPage.updateCart(options);
        }
    },
    updateDeliveryMethod: function (response, options) {
        const messageInfo = Wick.BasketPage.isMessageExist(response) && Wick.BasketPage.getMessageInfo(response);
        Object.assign(options, messageInfo);
        Wick.BasketPage.showNotification(response)
        Wick.BasketPage.updateCart(options);
    },
    removeOrderItem: function (messageInfo) {
        let currentLink = window.location.origin.concat(window.location.pathname),
            message = encodeURIComponent(messageInfo.message),
            status = messageInfo.status,
            link;

        link = `${currentLink}?notificationMessage=${message}&messageStatus=${status}`
        window.location.replace(link);
    },
    repaintOrderItems: function (data, message) {
        const ccGroup = data.pickupOrderGroups || [],
            deliveryGroup = data.deliveryOrderGroups || [];
        let type, itemDetails = {};

        $(Wick.BasketPage.el.orderItem).remove();

        if (ccGroup.length) {
            type = 'cc';
            if ($(Wick.BasketPage.el.basketCCSection).length) {
                ccGroup.forEach((obj) => {
                    obj.entries.forEach(item => {
                        itemDetails = {
                            item, type, data,
                        };
                        $(Wick.BasketPage.el.basketCCSection).append(Wick.BasketPage.createOrderItem(itemDetails));
                    })
                })
                Wick.BasketPage.updateItemsCount(data, type);
            } else {
                if ($(Wick.BasketPage.el.basketDeliverySection)) {
                    $(Wick.BasketPage.el.basketDeliverySection).after(Wick.BasketPage.createBasketSection(type, ccGroup, data))
                } else {
                    $(Wick.BasketPage.el.content).prepend(Wick.BasketPage.createBasketSection(type, ccGroup, data));
                }
            }
        } else {
            $(Wick.BasketPage.el.basketCCSection).remove();
        }

        if (deliveryGroup.length) {
            if (deliveryGroup.length === 1 && deliveryGroup[0].entries.length === 1 && deliveryGroup[0].entries[0].charity) {
                $(Wick.BasketPage.el.basketDeliverySection).remove();
            } else {
                type = 'delivery';

                if ($(Wick.BasketPage.el.basketDeliverySection).length) {
                    deliveryGroup.forEach((obj) => {
                        obj.entries.forEach(item => {
                            itemDetails = {
                                item, type, data,
                            };
                            $(Wick.BasketPage.el.basketDeliverySection).append(Wick.BasketPage.createOrderItem(itemDetails));
                        })

                    })
                    Wick.BasketPage.updateItemsCount(data, type);
                } else {
                    $(Wick.BasketPage.el.content).prepend(Wick.BasketPage.createBasketSection(type, deliveryGroup, data));
                }
            }
            Wick.BasketPage.addCharityEntryNumber(data);
        } else {
            $(Wick.BasketPage.el.basketDeliverySection).remove();
        }

        $('.order-item').each(function () {
            let quantity = +$(this).find('.order-item__quantity-value').val();
            Wick.BasketPage.toggleItemTotal(this, quantity)
        })

        Wick.BasketPage.paintActionButton();
        checkPayPalAvailability(data);
        $(document).trigger("cartRerender");
    },
    createBasketSection: function (type, group, data) {
        type === 'cc' ? type = 'Click & Collect' : type = 'Delivery';
        const orderItems = [];
        let itemDetails = {};

        group.forEach(obj => {
            obj.entries.forEach(item => {
                itemDetails = {item, type, data};
                orderItems.push(Wick.BasketPage.createOrderItem(itemDetails));
            })
        });

        const itemsCount = type === 'Click & Collect' ? data.pickupUniqueItemsNumber : data.deliveryUniqueItemsNumber;

        return `
            <section class="basket__section" data-type="${type}">
                <div class="checkout-title">
                    <h3 class="checkout-title__title">
                        ${type}
                    </h3>
                      <div class="checkout-title__items">
                        ${itemsCount} item${itemsCount > 1 ? 's' : ''}
                    </div>
                </div>
                ${orderItems.join('')}
            </section>
        `
    },
    updateItemsCount: function (data, type) {
        const itemCount = type === 'cc' ? data.pickupUniqueItemsNumber : data.deliveryUniqueItemsNumber,
            titleItemsText = `${itemCount} item${itemCount > 1 ? 's' : ''}`;

        if (type === 'cc') {
            $(Wick.BasketPage.el.basketCCSection).find(Wick.BasketPage.el.titleItems).text(titleItemsText)
        }

        if (type === 'delivery') {
            $(Wick.BasketPage.el.basketDeliverySection).find(Wick.BasketPage.el.titleItems).text(titleItemsText);
        }
    },
    createOrderItem: function (itemDetails) {
        const currentItem = itemDetails.item;

        if (!currentItem.charity) {
            return `
            <div class="order-item" data-id="${currentItem.entryNumber}">
                <div class="order-item__main">
                    <div class="order-item__image">
                        <a href="${currentItem.product.url}" class="oder-item__image-link">
                            <img 
                                src="${currentItem.product.image ? currentItem.product.image.url : '/'}" 
                                alt="${currentItem.product.image ? currentItem.product.image.altText : currentItem.product.name}"
                            >
                        </a>
                    </div>
                    <div class="order-item__info">
                        <div class="order-item__product">
                            <a href="${currentItem.product.url}" class="order-item__title">
                                ${currentItem.product.name}
                            </a>
                            ${displayEnergyEfficiency(currentItem.product?.energyEfficiencyInfo)}
                            <div class="order-item__code">
                                <span class="product-code">
                                    Product code:
                                    <span class="product-code-number">
                                        ${currentItem.product.code}
                                    </span>
                                </span>
                            </div>
                        </div>
                        ${currentItem.updateable ? Wick.BasketPage.addPromotions(currentItem, itemDetails.data) : ''}
                    </div>    
                    <div class="order-item__cost">
                        <div class="order-item__quantity">
                            <div class="order-item__quantity-title">
                                Quantity:
                            </div>
                            <div class="order-item__quantity-control">
                                <button class="btn order-item__quantity-btn" data-action="minus" ${currentItem.updateable || 'disabled'}>
                                    <span class="btn__text">
                                        <i class="fal fa-minus"></i>
                                    </span>
                                </button>
                                <label class="order-item__quantity-label">
                                    <input type="tel" 
                                           class="order-item__quantity-value tbx" 
                                           min="${currentItem.product.minOrderQuantity ? currentItem.product.minOrderQuantity : '0'}" 
                                           max="${currentItem.product.maxOrderQuantity ? currentItem.product.maxOrderQuantity : '99999'}" 
                                           value="${currentItem.quantity}"
                                           ${currentItem.updateable || 'disabled'}
                                    >
                                </label>
                                <button class="btn order-item__quantity-btn" data-action="plus" ${currentItem.updateable || 'disabled'}>
                                    <span class="btn__text">
                                        <i class="fal fa-plus"></i>
                                    </span>
                                </button>
                            </div>
                        </div>
                         <div class="order-item__price">
                            <div class="order-item__price-title">Item price:</div>
                            <div class="order-item__price-value">
                                <span class="order-item__value">
                                    ${currentItem.basePrice.value === 0 ? 'FREE' : currentItem.basePrice.formattedValue}
                                </span>
                            </div>
                        </div>
                        ${Wick.BasketPage.createPerMeterPrice(currentItem)}
                        <div class="order-item__total">
                            <div class="order-item__total-title">Item total:</div>
                            <div class="order-item__total-value">
                                <span class="order-item__value">
                                   ${currentItem.itemTotalWithoutDiscount.value === 0 ? 'FREE' : currentItem.itemTotalWithoutDiscount.formattedValue}
                                </span>
                            </div>
                        </div>
                        <button class="btn order-item__remove ${currentItem.updateable || 'd-none'}" data-action="remove">
                            <span class="btn__text">
                              <i class="fas fa-trash"></i>
                            </span>
                        </button>
                    </div>     
                    <div class="order-item__actions">
                        ${Wick.BasketPage.createActionButton(currentItem, 'delivery', itemDetails.type)}
                         ${Wick.BasketPage.createActionButton(currentItem, 'cc', itemDetails.type)}
                    </div>
                </div>
                ${createWisdom(currentItem)}
                ${Wick.BasketPage.createDeliveryMessage(currentItem, itemDetails.type)}
                ${Wick.BasketPage.createCCFinder(currentItem)}
            </div>
        `
        }
    },
    createActionButton: function (item, type, section) {
        let available,
            title,
            dataType;

        if (type === 'cc') {
            title = 'Click & Collect';
            dataType = 'Click & Collect';
            available = item.orderFulfilmentControls.availableForCollection;
        } else if (type === 'delivery') {
            if (item.orderFulfilmentControls.availableForDelivery) {
                title = 'For Delivery';
                dataType = 'Delivery';
                available = item.orderFulfilmentControls.availableForDelivery;
            }
            if (item.orderFulfilmentControls.availableForWickesFulfilment) {
                if (section.toLowerCase() === 'delivery') {
                    title = 'For Delivery';
                    dataType = 'Delivery';
                    available = item.orderFulfilmentControls.availableForWickesFulfilment;
                } else {
                    title = 'Check Delivery Stock';
                    dataType = 'Delivery Stock';
                    type = "delivery_stock";
                    available = item.orderFulfilmentControls.availableForWickesFulfilment;
                }
            }
        }

        if (available) {
            return `
            <div class="order-item__action ${item.updateable ? '' : 'disabled'}" data-type="${dataType}" >         
                <label class="rbn" for="btn-${item.entryNumber}-${type}">
                    <input 
                        type="radio" 
                        id="btn-${item.entryNumber}-${type}"
                        name="btn-${item.entryNumber}" 
                        ${item.updateable || 'disabled'}
                    >
                    <ins></ins> 
                    <span>${title}</span>
                </label>
            </div>
        `
        } else {
            return ''
        }

    },
    addPromotions: function (item, data) {
        let arr = [];

        data.potentialProductPromotions && data.potentialProductPromotions.forEach((entry) => {
            entry.consumedEntries.forEach((promo) => {
                if (promo.orderEntryNumber === item.entryNumber) {
                    if (arr.length) {
                        let duplicate = arr.every((el) => {
                            return el !== `<div class="order-line__promo">${entry.description}</div>`
                        })

                        !duplicate || arr.push(`<div class="order-line__promo">${entry.description}</div>`);

                    } else {
                        arr.push(`<div class="order-line__promo">${entry.description}</div>`);
                    }
                }
            })

        });

        data.appliedProductPromotions && data.appliedProductPromotions.forEach((entry) => {
            entry.consumedEntries.forEach((promo) => {
                if (promo.orderEntryNumber === item.entryNumber && entry.description) {
                    if (arr.length) {
                        let duplicate = arr.every((el) => {
                            return el !== `<div class="order-item__promo">${entry.description}</div>`
                        })

                        !duplicate || arr.push(`<div class="order-item__promo">${entry.description}</div>`);

                    } else {
                        arr.push(`<div class="order-item__promo">${entry.description}</div>`);
                    }
                }
            })
        });

        return arr.length ? `<div class="order-item__offers">${arr.join('')}</div>` : ''
    },
    createPerMeterPrice: function (item) {
        if (item.product.installationProduct) {
            return `
                <div class="order-item__price-m">
                    <div class="order-item__price-m-title">Per m<sup>2</sup>:</div>
                    <div class="order-item__price-m-value">
                        <span class="order-item__value">£${item.product.pricePerSqm.formattedPriceWithoutCurrencySymbol}</span>
                    </div>
                </div>
            `
        } else {
            return ''
        }
    },
    createDeliveryMessage: function (item, type) {
        if (type === 'delivery') {
            let currentFulfillment = item.product.fulfillmentAttributes.supplierDelivered ? 'SUPPLIER_DELIVERED' : 'STANDARD',
                productCode = item.product.code,
                coincidenceFulfillmentValue = $(Wick.BasketPage.el.content).find(`#${productCode}_${currentFulfillment}`).val()

            if (coincidenceFulfillmentValue) {
                return `
                    <div class="order-item__delivery">
                        <i class="order-item__delivery-icon fas fa-exclamation-circle"></i>
                        <div class="order-item__delivery-message">
                            ${coincidenceFulfillmentValue}
                        </div>
                    </div>
                    `
            } else {
                return ''
            }
        } else {
            return ''
        }
    },
    createCCFinder: function (item) {
        return `
            <div class="cc-order">
                <div class="cc-order__head">
                    ${Wick.BasketPage.checkStoreAvailability(item.deliveryPointOfService, item)}
                </div>
                ${Wick.BasketPage.createCCOrderInfo(item)}
            </div>
        `
    },
    createCCOrderInfo: function (item) {
        if (item.updateable) {
            return `
                <div class="cc-order__info ${item.deliveryPointOfService ? 'cc-order__info-hide' : ''} bw" data-product="${item.product.code}">
                        <div class="cc-order__close">
                            <a href="#" class="cc-order__close-link">
                                Close
                            </a>
                        </div>
                        <div class="cc-order__section cc-order__section-find">
                            <div class="cc-order__section-info">
                                <div class="stock__postcode">
                                    <label class="stock__postcode_label">
                                        <input type="text" class="stock__input tbx" name="bw-postcode" id="bw-postcode_${item.entryNumber}">
                                        <button class="btn btn-secondary stock__target" id="geoLocationIcon_${item.entryNumber}">
                                            <span class="btn__text">
                                                <i class="far fa-crosshairs"></i>
                                            </span>
                                        </button>
                                    </label>
                                    <span class="stock__postcode_invalid-msg">
                                        Check that you entered a valid postcode or place name.
                                    </span>
                                </div>
                                <div class="stock__quest">
                                    <label class="chb" for="stock-only_${item.entryNumber}">
                                        <input 
                                            type="checkbox" 
                                            value="" 
                                            id="stock-only_${item.entryNumber}" 
                                            name="stock-only_${item.entryNumber}" 
                                            checked="checked"
                                        >
                                        <ins><i class="fas fa-check"></i></ins>
                                        <span>Only show stores with stock.</span>
                                    </label>
                                    <label class="chb" for="cc-only_${item.entryNumber}">
                                        <input 
                                            type="checkbox"
                                            value=""
                                            id="cc-only_${item.entryNumber}"
                                            name="cc-only_${item.entryNumber}"
                                            name="cc-only" 
                                            checked="checked"
                                        >
                                        <ins><i class="fas fa-check"></i></ins>
                                        <span>Only show stores with Click & Collect.</span>
                                    </label>
                                </div>
                            </div>
                            <div class="cc-order__section-cta">
                                <button class="btn btn_full btn-primary" id="bw_pickupstore_search_button_${item.entryNumber}">
                                    <span class="btn__text">
                                        Find Stores
                                    </span>
                                </button>
                            </div>
                            <input type="hidden" name="findStores" value="/store-pickup/${item.product.code}/pointOfServices" class="findStores" />
                        </div>
                    </div>
                </div>
            `
        } else {
            return ''
        }
    },
    checkStoreAvailability: function (store, item) {
        if (store) {
            return `
                <div class="cc-order__store">
                    <i class="cc-order-icon fas fa-store"></i>
                    ${store.description}
                </div>
                <a href="#" class="cc-order__change" ${item.updateable || 'style="display: none"'}>
                    Change Store location
                </a>
            `
        } else {
            return `
                <div class="cc-order__store-select">
                    <div class="cc-order__store cc-order__store-unselected">
                        <i class="cc-order-icon fas fa-exclamation-circle"></i>
                        <a href="#">
                            Select store location
                        </a>
                    </div>
                </div>
            `
        }
    },
    removePromotion: function () {
        $(this).closest(Wick.BasketPage.el.promo).remove()
    },
    addPotentialPromo: function (data) {
        $(Wick.BasketPage.el.promo).remove();

        if ((data.potentialOrderPromotions && data.potentialOrderPromotions.length)
            || (data.appliedOrderPromotions && data.appliedOrderPromotions.length)) {
            $(Wick.BasketPage.el.promoWrapper).append(Wick.BasketPage.createPotentialPromo(data));
        }
    },
    createPotentialPromo: function (data) {
        const arr = [];
        if (data.potentialOrderPromotions && data.potentialOrderPromotions.length) {
            data.potentialOrderPromotions.forEach((promo) => {
                !promo.description || arr.push(`
                    <div class="p-promotion">
                        <div class="p-promotion__icon">
                            <i class="icon fas fa-gift"></i>
                        </div>
                        <div class="p-promotion__description">
                            ${promo.description}
                        </div>
                        <div class="p-promotion__close">
                            <i class="icon fas fa-times"></i>
                        </div>
                    </div>
                `
                )
            })
        }

        if (data.appliedOrderPromotions && data.appliedOrderPromotions.length) {
            data.appliedOrderPromotions.forEach((promo) => {
                !promo.description || arr.push(`
                    <div class="p-promotion">
                        <div class="p-promotion__icon">
                            <i class="icon fas fa-gift"></i>
                        </div>
                        <div class="p-promotion__description">
                            ${promo.description}
                        </div>
                        <div class="p-promotion__close">
                            <i class="icon fas fa-times"></i>
                        </div>
                    </div>
                `
                )
            })
        }
        if ($(Wick.BasketPage.el.promoWrapper).length) {
            return arr.join('');
        } else {
            $(Wick.BasketPage.el.checkoutHeader).before(`<div class="checkout-header__promo">${arr.join('')}</div>`)
        }
    },
    limitingQuantityValue: function () {
        const charactersLimit = 5,
            context = $(this).closest(Wick.BasketPage.el.orderItem);

        if (this.value !== '') {
            this.value = this.value.replace(/\D/g, '');
        }

        if (this.value.length > charactersLimit) {
            this.value = this.value.slice(0, charactersLimit);
        }

        context.find(Wick.BasketPage.el.actionButton).addClass('disabled');
    },
    makeRadioActive: function (el) {
        const item = $(el).closest(Wick.BasketPage.el.orderItem);
        item.find(Wick.BasketPage.el.actionButton).removeClass(Wick.BasketPage.el.btnSelected);
        $(el).addClass(Wick.BasketPage.el.btnSelected);
        $(el).find('input').prop('checked', true);
    },
    changeAccordionText: function () {
        Wick.BasketPage.debounceChangeAccordionText(this);
    },
    debounceChangeAccordionText: _.debounce(function (context) {
        const showText = 'Show full summary',
            hideText = 'Hide full summary';
        const collapsed = $(context).hasClass('collapsed');
        const accordionText = collapsed ? showText : hideText;

        $(context).find(Wick.BasketPage.el.summaryAccordionText).text(accordionText)
    }, 150),
    changeOnBlur: function () {
        const context = $(this).closest(Wick.BasketPage.el.orderItem),
            entryNumber = +context.attr('data-id'),
            quantityInput = context.find(Wick.BasketPage.el.quantityValue);
        let value;

        Wick.BasketPage.cartEntries.forEach((el) => {
            if (el.entryNumber === entryNumber) {
                value = el.quantity;
            }
        });

        if (+this.value === 0) {
            context.find(Wick.BasketPage.el.actionButton).removeClass('disabled');
            quantityInput.val(value);
        }
    },
    addQuantityDisable(context) {
        $(context)
          .find(Wick.BasketPage.el.orderItemQuantityControl)
          .addClass(Wick.BasketPage.el.orderItemQuantityControlDisabledClass);
    },
    removeQuantityDisable(context) {
        $(Wick.BasketPage.el.content)
          .find(Wick.BasketPage.el.orderItemQuantityControl)
          .removeClass(Wick.BasketPage.el.orderItemQuantityControlDisabledClass);
    }
};
$(document).ready(function () {
    function init() {

        if (!$('.page_basket.basket').length) {
            return;
        }

        addStorageCheckEvent();
        Wick.BasketPage.el.$voucherFormBtn.on('click', checkVoucherCode);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.quantityButton, Wick.BasketPage.updateItemQuantity);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.removeButton, Wick.BasketPage.updateItemQuantity);
        $(Wick.BasketPage.el.content).on('change', Wick.BasketPage.el.quantityValue, Wick.BasketPage.updateItemQuantity);
        $(Wick.BasketPage.el.content).on('input', Wick.BasketPage.el.quantityValue, Wick.BasketPage.limitingQuantityValue);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.ccButton, Wick.BasketPage.showCCSectionInDelivery);
        $(Wick.BasketPage.el.content).on('focusout', Wick.BasketPage.el.quantityValue, Wick.BasketPage.changeOnBlur);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.deliveryButtonInCC, Wick.BasketPage.changeMethodToDelivery);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.updateStoreButton, Wick.BasketPage.changeMethodToCC);
        $(Wick.BasketPage.el.charityInput).on('click', updateCharity);
        $(Wick.BasketPage.el.donationCartBtn).on('click', changeCharityPrice);
        $(Wick.BasketPage.el.charityItem).on('click', Wick.BasketPage.el.removeButton, updateCharity);
        $(Wick.BasketPage.el.orderSummary).on('click', Wick.BasketPage.el.voucherRemove, voucherRemove);
        $(Wick.BasketPage.el.promoWrapper).on('click', Wick.BasketPage.el.promoClose, Wick.BasketPage.removePromotion);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.deliveryStockButton, toggleWisdom);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.wisdomClose, toggleWisdom);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.wisdomCheck, checkDeliveryStock);
        $(Wick.BasketPage.el.content).on('keypress', Wick.BasketPage.el.wisdomPostcode, checkDeliveryStockOnEnter);
        $(Wick.BasketPage.el.content).on('blur', Wick.BasketPage.el.wisdomPostcode, prettifyWisdomPostcode);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.wisdomAdd, addDeliveryStock);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.changeLink, Wick.Wisdom.onLinkChange);
        $(Wick.BasketPage.el.content).on('click', Wick.BasketPage.el.summaryAccordion, Wick.BasketPage.changeAccordionText);
        $('main').on('click', Wick.BasketPage.el.promoClose, Wick.BasketPage.removePromotion);

        $(Wick.BasketPage.el.voucherRemove).unbind('click');
        Wick.BasketPage.paintActionButton();
        Wick.BasketPage.updateCart(...Array(3), true);
        setDefaultCharityValue();
        if (!$(Wick.BasketPage.el.loader).length) {
            appendLoader(Wick.BasketPage.loaderPayload);
        }

        if (Wick.checkLocalEnv) {
            Wick.BasketPage.loadIndexing();
        }
    }

    init();
});
