import {updateOrderSummary} from '../order-summary';
import {callAction} from '../http-action';

const voucherEl = {
    $voucherFormInput: $('#form-checkout-voucher #voucher-code'),
    $voucherForm: $('#form-checkout-voucher'),
    $basketVoucher: $('.checkout-voucher'),
    discountValue: '.checkout-widget__detail-value',
    orderTotalValue: '.checkout-widget__total-value',
    value: '.checkout-widget__item-value',
    formInvalid: 'form_invalid',
    fieldRow: '.form-row[data-row-required]',
    rowValidationError: 'form-row_validation-error',
    voucherHide: '.checkout-voucher-hide',
    fieldError: '.form-row__error',
    subtotal: '.checkout-widget__item-bold',
    vat: '.checkout-widget__item-vat',
    cc: '.checkout-widget__item-cc',
    delivery: '.checkout-widget__item-delivery',
    charity: '.checkout-widget__item-charity',
    discountItem: '.checkout-widget__details-discount',
    orderTotal: '.checkout-widget__total',
}

export function checkVoucherCode(e) {
    e.preventDefault()
    let value = voucherEl.$voucherFormInput.val();
    if (!Wick.chechLocalEnv) {
        const payload = {
            link: '/checkout/hybrid/apply-voucher',
            type: 'POST',
            data: {voucherCode: value},
        };
        callAction(payload, executionVoucherApplying)
    } else {
        //local usage
        if (Wick.BasketData.validPostCodes().includes(value)) {
            applyVoucher(Wick.BasketData.successVoucherData);
        } else {
            notApplyVoucher(Wick.BasketData.failVoucherData);
        }
    }
}

function executionVoucherApplying(data) {
    if (data.status === "SUCCESS") {
        applyVoucher(data);
    } else if (data.status === "FAIL") {
        notApplyVoucher(data);
    }
}

export function voucherRemove() {
    let voucher = $(this).parent(),
        voucherCode = voucher.attr('data-coupon-code');
    voucher.addClass('checkout-widget__voucher-removed').text('Voucher removed');
    voucherRemoveAction(voucherCode, voucher)
}

function voucherRemoveAction(code) {
    if (!Wick.chechLocalEnv) {
        const payload = {
            link: '/checkout/hybrid/release-voucher',
            type: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({voucherCode: code}),
        };
        callAction(payload, executionVoucherRemoving)
    } else {
        //local usage
        executionVoucherRemoving(Wick.BasketData.successVoucherData)
    }
}

function executionVoucherRemoving(data) {
    if (data.status === "SUCCESS") {
        updateOrderSummary(
            data.orderSummaryData,
            getEqualMapForVoucherUpdate(data),
            true
        );
    }
}

function applyVoucher(data) {
    clearValidationErrors(voucherEl.$voucherForm);
    voucherEl.$basketVoucher.toggle(voucherEl.voucherHide);
    updateOrderSummary(
        data.orderSummaryData,
        getEqualMapForVoucherUpdate(data),
        true
    );
    setTimeout(function () {
        voucherEl.$voucherFormInput.val('');
        voucherEl.$basketVoucher.toggle(voucherEl.voucherHide);
    }, 5000)
}

function notApplyVoucher(data) {
    showValidationErrors(voucherEl.$voucherForm, data.errorMessage);
}

function clearValidationErrors(form) {
    var $form = $(form);
    if ($form.hasClass(voucherEl.formInvalid)) {
        $form.removeClass(voucherEl.formInvalid)
            .find(voucherEl.fieldRow).removeClass(voucherEl.rowValidationError)
            .find(voucherEl.fieldError).remove();
    }
}

function showValidationErrors(form, errorMsg) {
    var $form = $(form);
    if (!$form.hasClass(voucherEl.formInvalid)) {
        $form.find('.form-row__error').remove();
        $form.addClass(voucherEl.formInvalid).find(voucherEl.fieldRow).append(validationError(errorMsg)).addClass(voucherEl.rowValidationError);
    }

    var $firstMsg = $form.find(voucherEl.fieldRow).first();
    if ($firstMsg.length && !isElementInViewport($firstMsg)) {
        var inModal = $firstMsg.closest('.modal').length,
            $scrollableEl = inModal ? $firstMsg.closest('.modal') : $('html, body'),
            y = inModal ? 0 : $firstMsg.offset().top - 30;

        $scrollableEl.animate({scrollTop: y}, 300);
    }
}

function isElementInViewport(el) {
    if (typeof jQuery === 'function' && el instanceof jQuery) {
        el = el[0];
    }
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

function validationError(errorMsg) {
    return `<div class="form-row__error"> ${errorMsg || 'Error message here'}</div>`
}

function getEqualMapForVoucherUpdate(data) {
    return [
        {
            item: voucherEl.subtotal,
            itemValue: voucherEl.value,
            dataValue: data.orderSummaryData.subTotal,
            title: 'Items Subtotal:'

        },
        {
            item: voucherEl.vat,
            itemValue: voucherEl.value,
            dataValue: data.orderSummaryData.vat,
            title: 'Includes VAT:'
        },
        {
            item: voucherEl.cc,
            itemValue: voucherEl.value,
            dataValue: data.orderSummaryData.clickAndCollectCost,
            title: 'Click & Collect:'
        },
        {
            item: voucherEl.delivery,
            itemValue: voucherEl.value,
            dataValue: data.orderSummaryData.deliveryCost,
            title: 'Delivery:'
        },
        {
            item: voucherEl.charity,
            itemValue: voucherEl.value,
            dataValue: data.orderSummaryData.charityPrice,
            title: 'Young Minds donation:'
        },
        {
            item: voucherEl.discountItem,
            itemValue: voucherEl.discountValue,
            dataValue: data.orderSummaryData.discountTotal
        },
        {
            item: voucherEl.orderTotal,
            itemValue: voucherEl.orderTotalValue,
            dataValue: data.orderSummaryData.total
        },
    ];
}

