import { updateDiscount } from './discounts';

const osEl = {
    $summarySection: $('.summary'),
    checkoutWidgetDetailsDiscount: '.checkout-widget__details-discount',
    checkoutWidgetDetails: '.checkout-widget__details',
    delivery: '.checkout-widget__item-delivery',
    deliveryCostMessage: '.checkout-widget__item-delivery-cost-message',
    cc: '.checkout-widget__item-cc',
    itemFree: '.checkout-widget__item-free',
    itemDeficit: '.checkout-widget__item-deficit',
    summaryDelivery: '.checkout-widget__item-delivery',
    summaryMobileTotal: '.summary__mobile-bar-total',
};

export function updateOrderSummary(data, equalMap, isVoucher) {
    equalMap.forEach((obj) => {
        if (typeof obj.dataValue === 'undefined') return;

        if ($(obj.item).length) {
            $(obj.item).show();
        } else {
            if ($(osEl.checkoutWidgetDetailsDiscount).length) {
                $(osEl.checkoutWidgetDetailsDiscount).before(createCheckoutWidgetItem(obj));
            } else {
                $(osEl.checkoutWidgetDetails).append(createCheckoutWidgetItem(obj));
            }
        }

        if (obj.item === osEl.delivery) {
            $(osEl.delivery).each(function () {
                if (
                    !$(this).siblings(osEl.deliveryCostMessage).length &&
                    !$(this).closest('[data-hide-delivery-cost-message]').length
                ) {
                    $(this).after(`
                      <li class="checkout-widget__item checkout-widget__item-delivery-cost-message">
                        <span class="checkout-widget__item-value" id="order-delivery-cost-message">
                          Final delivery cost confirmed at checkout
                        </span>
                      </li>`);
                }
            });
        }

        $(obj.item).find(obj.itemValue).text(obj.dataValue);
        if (isVoucher ? obj.dataValue : obj.value && obj.dataValue) {
            $(obj.item).find(obj.itemValue).show();
        } else {
            $(obj.item).hide();
        }
    });

    const keys = new Set(Object.keys(data || {}));
    const hasAny = (...arr) => arr.some((k) => keys.has(k));

    const value = data.totalPrice?.formattedValue || data.total;
    if (typeof value !== 'undefined' && hasAny('total', 'totalPrice')) {
        updateSummaryMobileBarTotal(value);
    }

    if (hasAny('promotionsInfo')) {
        updateDiscount(data, isVoucher);
    }

    if (
        hasAny(
            'deliveryOrder',
            'clickAndCollectOrder',
            'clickAndCollectOnly',
            'deliveryItemsQuantity',
            'pickupItemsQuantity'
        )
    ) {
        hideUnusedDeliveryTypeCost(data, isVoucher);
    }

    if (hasAny('freeDelivery', 'messageForFreeDelivery', 'clickAndCollectOnly')) {
        calculateFreeDelivery(data);
    }
}

function createCheckoutWidgetItem(obj) {
    const isDelivery = obj.item === osEl.delivery;
    const hideMessage = $(osEl.checkoutWidgetDetails).closest(
        '[data-hide-delivery-cost-message]'
    ).length;
    const costMessageExists = $(osEl.deliveryCostMessage).length > 0;
    return `
      <li class="checkout-widget__item ${obj.item.substr(1)}">
        <span>${obj.title}</span>
          <span class="checkout-widget__item-value">${obj.dataValue}</span>
      </li>
      ${
          isDelivery && !hideMessage && !costMessageExists
              ? `
      <li class="checkout-widget__item checkout-widget__item-delivery-cost-message">
        <span class="checkout-widget__item-value" id="order-delivery-cost-message">
          Final delivery cost confirmed at checkout
        </span>
      </li>`
              : ''
      }
    `;
}

function hideUnusedDeliveryTypeCost(data, isVoucher) {
    $(osEl.delivery).show();
    $(osEl.deliveryCostMessage).show();
    $(osEl.cc).show();
    if (isVoucher) {
        if ('deliveryOrder' in data && data.deliveryOrder === false) {
            $(osEl.delivery).hide();
            $(osEl.deliveryCostMessage).hide();
        }

        if ('clickAndCollectOrder' in data && data.clickAndCollectOrder === false) {
            $(osEl.cc).hide();
        }
    } else {
        if (data.clickAndCollectOnly) {
            $(osEl.delivery).hide();
            $(osEl.deliveryCostMessage).hide();
        } else if (data.deliveryItemsQuantity > 0 && data.pickupItemsQuantity === 0) {
            $(osEl.cc).hide();
        }
    }
}

function calculateFreeDelivery(data) {
    osEl.$summarySection.each(function () {
        let $free = $(this).find(osEl.itemFree);
        let $deficit = $(this).find(osEl.itemDeficit);

        !$free.length || $free.remove();
        !$deficit.length || $deficit.remove();

        if (!data.clickAndCollectOnly) {
            if (data.freeDelivery && data.messageForFreeDelivery) {
                $(this)
                    .find(osEl.summaryDelivery)
                    .before(function () {
                        return `
                        <div class="checkout-widget__item checkout-widget__item-free">
                            <span class="checkout-widget__text">
                               ${data.messageForFreeDelivery}
                            </span>
                        </div>
                    `;
                    });
                $(this).find(osEl.summaryDelivery).hide();
            } else if (!data.freeDelivery && data.messageForFreeDelivery) {
                $(this)
                    .find(osEl.summaryDelivery)
                    .before(function () {
                        return `
                        <div class="checkout-widget__item checkout-widget__item-deficit">
                            ${data.messageForFreeDelivery}
                        </div>
                    `;
                    });
            }
        }
    });
}

function updateSummaryMobileBarTotal(formattedValue) {
    $(osEl.summaryMobileTotal).text(formattedValue);
}
