'use strict';

var base = require('base/checkout/billing');
var cleave = require('base/components/cleave');
var redsysHelper = require('./redsysHelper');

/**
 * Extra validation for Redsys iframe
 * @returns {boolean} true/false
 */
base.customValidations = function () {
    // Validate email in payment step.
    var email = $('#email').val();
    var emailRegex = /^[\w.%+-]+@[\w.-]+\.[\w]{2,6}$/;
    if (email && $('#dwfrm_billing #email').length && !emailRegex.test(email)) {
        // If email field is wrong, submit payment form to launch sfra standard validations
        $('.submit-payment').click();
        return false;
    }

     // Validate phone number in payment step.
    var phone = $('phoneNumber').val();
    // eslint-disable-next-line no-useless-escape
    var phoneRegex = /^(([0-9]{2,4})([-\s\/]{0,1})([0-9]{4,8}))?$/;
    if (phone && $('#dwfrm_billing #phoneNumber').length && !phoneRegex.test(phone)) {
        // If phoneNumber field is wrong, submit payment form to launch sfra standard validations
        $('.submit-payment').click();
        return false;
    }

    return true;
};

/**
 * @function changePaymentMethod
 * @description Change payment method option
 */
base.updatePaymentMethodId = function () {
    $('.payment-options .nav-link').click(function setAttr() {
        $('#selectedPaymentOption').val($(this).parent().attr('data-method-id'));
    });
};

/**
 * @function handleCreditCardNumber
 * @description Handle credit card number
 */
base.handleCreditCardNumber = function () {
    if ($('.cardNumber').length > 0 && $('#cardType').length > 0) {
        cleave.handleCreditCardNumber('.cardNumber', '#cardType');
    }
};

/**
 * @function changePaymentMethod
 * @description Change payment method option
 */
base.changePaymentMethod = function () {
    $('.payment-options a[data-toggle="tab"]').on('click', function () {
        var activePaymentMethod = $(this).attr('href');
        var activePaymentMethodName = $(this).parent().attr('data-method-id');
        var paymentMethods = $('.payment-options a[data-toggle="tab"]');

        if (activePaymentMethod && activePaymentMethodName) {
            redsysHelper.setPaymentMethodId(activePaymentMethodName);
        }

        var inSitePaymentElement = $('#redsys-credit-card-form-inSite').length;
        var hasSavedPaymentInstruments = $('.saved-payment-instrument').length > 0;
        if (activePaymentMethodName === 'REDSYS_CREDIT_CARD' &&
            inSitePaymentElement) {
            if (!$('#redsys-hosted-pay-button').length) {
                redsysHelper.renderRedsysInSiteForm();
                $('button[value=submit-payment]').addClass('d-none');
            }
            if ($('#refresh-credit-card-payment').hasClass('checkout-hidden')) {
                if ($('.user-payment-instruments.container').hasClass('checkout-hidden')) {
                    $('button[value=submit-payment]').addClass('d-none');
                } else {
                    $('button[value=submit-payment]').removeClass('d-none');
                    $('.cancel-new-payment').addClass('checkout-hidden');
                }
                if (!hasSavedPaymentInstruments) {
                    $('button[value=submit-payment]').addClass('d-none');
                }
            } else {
                $('button[value=submit-payment]').addClass('d-none');
            }
        } else {
            $('button[value=submit-payment]').removeClass('d-none');
        }

        paymentMethods.each(function (i, paymentMethod) {
            var payment = $(paymentMethod).attr('href');
            $(payment).find('input, select, button').prop('disabled', payment !== activePaymentMethod);
        });
    });
};

/**
 * @function setDefaultPaymentMethod
 * @description Set active one payment method if not exist
 */
base.setDefaultPaymentMethod = function () {
    var activePaymentMethodId = redsysHelper.getPaymentMethodId();

    if (!activePaymentMethodId) {
        var paymentMethods = $('.payment-options a[data-toggle="tab"]');
        paymentMethods.each(function (i, paymentMethod) {
            $(paymentMethod).trigger('click');
            return false;
        });
    }
};

/**
 * @function reloadCreditCardIframe
 * @description Reload credit card iframe when user click on button to enter credit card data again
 */
base.reloadCreditCardIframe = function () {
    $('#refresh-credit-card-payment').on('click', function () {
        $('#refresh-credit-card-payment').addClass('checkout-hidden');
        $('#redsys-hosted-pay-button').remove();
        $('#creditCardToken').val('');
        var hasSavedPaymentInstruments = $('.saved-payment-instrument').length > 0;
        var activePaymentMethodId = redsysHelper.getPaymentMethodId();
        if (activePaymentMethodId === 'REDSYS_CREDIT_CARD' && hasSavedPaymentInstruments) {
            $('.save-credit-card').removeClass('checkout-hidden');
        }
        redsysHelper.renderRedsysInSiteForm();
        $('button[value=submit-payment]').addClass('d-none');
    });
};

base.addNewPaymentInstrument = function () {
    $('.btn.add-payment').on('click', function (e) {
        e.preventDefault();
        $('#refresh-credit-card-payment').click();
        $('.payment-information').data('is-new-payment', true);
        $('.credit-card-form').removeClass('checkout-hidden');
        $('.user-payment-instruments').addClass('checkout-hidden');
        $('#redsys-hosted-pay-button').removeClass('checkout-hidden');
        $('.save-credit-card').removeClass('checkout-hidden');

        var activePaymentMethodId = redsysHelper.getPaymentMethodId();
        if (activePaymentMethodId === 'REDSYS_CREDIT_CARD') {
            var inSitePaymentElement = $('#redsys-credit-card-form-inSite').length;
            if (inSitePaymentElement) {
                $('#redsys-hosted-pay-button').removeClass('checkout-hidden');
                $('button[value=submit-payment]').addClass('d-none');
            } else {
                $('.save-credit-card').removeClass('checkout-hidden');
            }
            var hasSavedPaymentInstruments = $('.saved-payment-instrument').length > 0;
            if (hasSavedPaymentInstruments) {
                $('.cancel-new-payment').removeClass('checkout-hidden');
            }
        } else {
            base.methods.clearCreditCardForm();
        }
    });
};

base.cancelNewPayment = function () {
    $('.cancel-new-payment').on('click', function (e) {
        e.preventDefault();
        if ($('.user-payment-instruments.container').hasClass('checkout-hidden')) {
            $('.cancel-new-payment').removeClass('checkout-hidden');
        } else {
            $('.cancel-new-payment').addClass('checkout-hidden');
        }
        $('.security-code-input').removeClass('checkout-hidden');
        $('.payment-information').data('is-new-payment', false);
        $('.user-payment-instruments').removeClass('checkout-hidden');
        $('.credit-card-form').addClass('checkout-hidden');
        var hasSavedPaymentInstruments = $('.saved-payment-instrument').length > 0;
        var activePaymentMethodId = redsysHelper.getPaymentMethodId();
        if (activePaymentMethodId !== 'REDSYS_CREDIT_CARD') {
            base.methods.clearCreditCardForm();
        }
        if (hasSavedPaymentInstruments) {
            $('button[value=submit-payment]').removeClass('d-none');
        }
        if (!$('.user-payment-instruments').hasClass('checkout-hidden')) {
            $('#refresh-credit-card-payment').addClass('checkout-hidden');
            $('.cancel-new-payment').addClass('checkout-hidden');
        }
        var inSitePaymentElement = $('#redsys-credit-card-form-inSite').length;
        if (!inSitePaymentElement) {
            $('.save-credit-card').addClass('checkout-hidden');
        }
    });
};

base.selectSavedCreditCard = function () {
    $('.saved-payment-instrument').on('click', function () {
        if ($('.saved-payment-instrument').length > 1) {
            $('.cancel-new-payment').removeClass('checkout-hidden');
        }
    });
};

/**
 * Validate and update payment instrument form fields
 * @param {Object} order - the order model
 */
base.methods.validateAndUpdateBillingPaymentInstrument = function (order) {
    var activePaymentMethodId = redsysHelper.getPaymentMethodId();

    if (!order || activePaymentMethodId === 'REDSYS_CREDIT_CARD' ||
        activePaymentMethodId === 'REDSYS_BIZUM') {
        return;
    // eslint-disable-next-line no-else-return
    } else {
        var billing = order.billing;
        if (!billing.payment || !billing.payment.selectedPaymentInstruments
            || billing.payment.selectedPaymentInstruments.length <= 0) return;

        var form = $('form[name=dwfrm_billing]');
        if (!form) return;

        var instrument = billing.payment.selectedPaymentInstruments[0];
        $('select[name$=expirationMonth]', form).val(instrument.expirationMonth);
        $('select[name$=expirationYear]', form).val(instrument.expirationYear);
        // Force security code and card number clear
        $('input[name$=securityCode]', form).val('');
        $('input[name$=cardNumber]').data('cleave').setRawValue('');
    }
};

/**
 * Updates the payment information in checkout, based on the supplied order model
 * @param {Object} order - checkout model to use as basis of new truth
 */
base.methods.updatePaymentInformation = function (order) {
    // update payment details
    var $paymentSummary = $('.payment-details');
    var htmlToAppend = '';

    if (order.billing.payment && order.billing.payment.selectedPaymentInstruments
        && order.billing.payment.selectedPaymentInstruments.length > 0) {
        if (order.billing.payment.selectedPaymentInstruments[0].paymentMethod === 'CREDIT_CARD') {
            htmlToAppend += '<span>' + order.resources.cardType + ' '
                + order.billing.payment.selectedPaymentInstruments[0].type
                + '</span><div>'
                + order.billing.payment.selectedPaymentInstruments[0].maskedCreditCardNumber
                + '</div><div><span>'
                + order.resources.cardEnding + ' '
                + order.billing.payment.selectedPaymentInstruments[0].expirationMonth
                + '/' + order.billing.payment.selectedPaymentInstruments[0].expirationYear
                + '</span></div>';
        } else if (order.billing.payment.selectedPaymentInstruments[0].paymentMethod === 'REDSYS_BIZUM' ||
        order.billing.payment.selectedPaymentInstruments[0].paymentMethod === 'REDSYS_CREDIT_CARD') {
            htmlToAppend += '<span>'
            + order.resources.cardType
            + '</span><br/>';
        }
        $paymentSummary.empty().append(htmlToAppend);
    }
};

if ($('#redsys-credit-card-form-inSite').length) {
    window.addEventListener('message', function receiveMessage(event) {
        // eslint-disable-next-line no-undef
        storeIdOper(event, 'creditCardToken', 'creditCardErrorCode', base.customValidations);
        var creditCardToken = document.getElementById('creditCardToken');
        if (creditCardToken && creditCardToken.value !== '') {
            $('.submit-payment').click();
        }
    });
}

module.exports = base;
