jQuery(
	function ($) {
		const body = $( 'body' );
		const $orderReview = $('form#order_review');
    var orderPay = false;
		var checkoutForm = $('form.woocommerce-checkout');
		var instanceId, customer, merchantTrxId, transactionCallback

		body.on(
			'checkout_error',
			function (e) {
				console.error( e );
			}
		);
		body.on(
			'message',
			function (e) {
				console.log( e );
			}
		);

		$( 'form.checkout' ).on(
			'change',
			'input[name="payment_method"]',
			function () {
				$( document.body ).trigger( 'update_checkout' );
			}
		);

		body.on(
			'init_checkout',
			function () {
				renderCashier();
			}
		);

		body.on(
			'updated_checkout',
			function () {
				renderCashier();
			}
		);

    if( $( document.body ).hasClass( 'woocommerce-order-pay' ) ) {
      checkoutForm = $orderReview;
      orderPay = true;

			renderCashier()

			$orderReview.on(
				'change',
				'input[name="payment_method"]',
				function () {
					renderCashier()
				});
    }

		function renderCashier() {
			var paymentOption = document.getElementById( 'payment-option-easypaymentgateway' );

			if (null === paymentOption || 'undefined' === (typeof paymentOption)) {
				return;
			}

			instanceId = paymentOption.getAttribute( 'data-instance' );
			customer   = paymentOption.getAttribute( 'data-customer' );

			var token          = paymentOption.getAttribute('data-token')
			var url            = paymentOption.getAttribute('data-api-base')
			var type_financing = paymentOption.getAttribute('data-financing')
			var data_currency  = paymentOption.getAttribute('data-currency')
			var data_language  = paymentOption.getAttribute('data-language')
			var data_locale    = paymentOption.getAttribute('data-locale')
			var data_decsep    = paymentOption.getAttribute('data-decsep')
			var data_thosep    = paymentOption.getAttribute('data-thosep')
			var data_amount    = paymentOption.getAttribute('data-amount')

			data_locale = data_locale.replace("_", "-");
			data_amount = data_amount * 100;

			$( '#epgjs-cashier-div' ).html( '' );

			try {
				EPGJS_COMM.setEpgBaseUrl( url );
				EPGJS.setShowAllPaysolToRegisterAndQuickDeposit( true );
				EPGJS_STYLE.setCssTheme( EPGJS_STYLE.DEFAULT_BOOTSTRAP_THEME );
				EPGJS_COMM.setMerchantRegisterAccountCallback( registerAccountCallback );
				EPGJS_COMM.setRegisterAccountErrorCallback( registerAccountErrorCallback );
				EPGJS_COMM.setMerchantPrePayCallback( prepayCallback );

				EPGJS.setPrePayAccountErrorCallback( prepayErrorCallback );

				EPGJS_I18N.setLang( allPaySol_object.locale );
				EPGJS_I18N.setI18n( allPaySol_object.i18n );

				// $( window ).on(
				// 	'message',
				// 	function (e) {
				// 		console.log( e );
				// 	}
				// );

				EPGJS.renderIntegratedCashier( token, 'epgjs-cashier-div' );

				EPGJS.setInitPaysolParam({
					"amount": data_amount,
					"currency": data_currency,
					"language": data_language,
					"locale": data_locale,
					"decimalSeparator": data_decsep,
					"thousandSeparator": data_thosep,
					"widgetCheckoutStyle": {"color": "#4CC6CD", "branding": "lending_hub"},
					"widgetSimulationConditionsProduct": type_financing,
					"widgetSimulationStyle": "width: 100%;text-align:center",
					"widgetSimulationBranding": "lending_hub",
					"widgetSimulationVariant": "select",
					"widgetSimulationColor": "#f4aeeb"
				});

			} catch (error) {
				console.error( error );
				alert( 'error' );
			}
		}

		function prepayCallback(prepayData) {
			var paymentMethod = document.getElementById('addonForm');
			var rememberMeInput = document.querySelector('#epgjs_paymentmethod_payment_container input[name = "rememberMe"]');

			var prepayElement = $( '<input>' ).attr(
				{
					id: 'wp-easypaymentgateway-prepay-' + instanceId + '__response',
					type: 'hidden',
					name: 'prepayResponse'
				}
			);

			prepayData.customerId    = customer;
			prepayData.paymentMethod = paymentMethod.getAttribute('data-pmname').toLowerCase();
			prepayData.rememberMe    = rememberMeInput !== null && !!rememberMeInput.checked;

			prepayElement.val( JSON.stringify( prepayData ) );
			prepayElement.appendTo( checkoutForm );

			if ('quix' === prepayData.paymentMethod) {
				nemuru_checkout.submit()
			} else {
				checkoutForm.submit();
			}
		}

		function prepayErrorCallback(data) {
			try {
				switch (true) {
					case (data.message.indexOf( 'expired' ) !== -1):
						var expired = $( '#addonpayments-expired' );
						expired.removeClass( 'hidden' );
						break;
					default:
						var error = $( '#addonpayments-error' );
						error.html( allPaySol_object.texts.unknownError );
						error.removeClass( 'hidden' );
						console.debug( data );
				}
			} catch (e) {
				console.error( e );
			}
		}

		function nemuruStatusCallback() {
			 window.location.replace(transactionCallback)
		}

		function registerAccountCallback(payload) {
			if ('CreditCards' !== payload.paymentMethod) {
				return;
			}

			var paymentOption = document.getElementById( 'payment-option-easypaymentgateway' );

			if (null === paymentOption || 'undefined' === (typeof paymentOption)) {
				return;
			}

			payload.customer = allPaySol_object.customerId;
			$.ajax(
				{
					method: "POST",
					url: paymentOption.getAttribute( 'data-register-callback' ),
					data: {
						action: 'card-vault',
						registerResponse: payload
					},
					success: function (result) {
						result = JSON.parse( result );
						if (result['status'] != 'success') {
							console.error( result );
							var error = $( '#addonpayments-error' );
							error.html( result['msg'] );
							error.removeClass( 'hidden' );
						}
					}
				}
			);
		}

		function registerAccountErrorCallback(data) {
			try {
				switch (true) {
					case (data.message.indexOf( 'expired' ) !== -1):
						var expired = $( '#addonpayments-expired' );
						expired.removeClass( 'hidden' );
						break;
					case (data.message.indexOf( 'Reached limit accounts for the paysol' ) !== -1):
						var error = $( '#addonpayments-error' );
						error.html( allPaySol_object.texts.reachedPaysolLimit );
						error.removeClass( 'hidden' );
						break;
					default:
						var error = $( '#addonpayments-error' );
						error.html( allPaySol_object.texts.unknownError );
						error.removeClass( 'hidden' );
						console.debug( data );
				}
			} catch (e) {
				console.error( e );
			}
		}

		const nemuru_checkout = {
			$checkout_form: checkoutForm,
			is_valid_json: function (raw_json) {
				try {
					var json = JSON.parse(raw_json)

					return ( json && 'object' === typeof json )
				}
				catch (e) {
					return false
				}
			},
			blockOnSubmit: function ($form) {
				var isBlocked = $form.data('blockUI.isBlocked')

				if (1 !== isBlocked) {
					$form.block({
						message: null,
						overlayCSS: {
							background: '#fff',
							opacity: 0.6
						}
					})
				}
			},
			submit: function () {
				var $form = this.$checkout_form

				if ( $form.is( '.processing' ) ) {
					return false;
				}

				$form.addClass( 'processing' );

				this.blockOnSubmit( $form );

				$.ajaxSetup({
					dataFilter: function (raw_response, dataType) {
						// We only want to work with JSON
						if ('json' !== dataType) {
							return raw_response
						}

						if (nemuru_checkout.is_valid_json(raw_response)) {
							return raw_response
						}
						else {
							// Attempt to fix the malformed JSON
							var maybe_valid_json = raw_response.match(/{"result.*}/)

							if (null === maybe_valid_json) {
								console.log('Unable to fix malformed JSON')
							}
							else if (nemuru_checkout.is_valid_json(maybe_valid_json[0])) {
								console.log('Fixed malformed JSON. Original:')
								console.log(raw_response)
								raw_response = maybe_valid_json[0]
							}
							else {
								console.log('Unable to fix malformed JSON')
							}
						}

						return raw_response
					}
				})

				var data = {
          	type: 'POST',
						data: $form.serialize(),
						dataType: 'json',
        };

        if(!orderPay) {
          data.url = wc_checkout_params.checkout_url;
        }

				this.send_form( data )
					.done(function(result) {
						try {
							if ('success' === result.result) {
								var data = result.paymentResponse

								merchantTrxId       = data.merchantTrxId
								transactionCallback = data.callback

								NEMURU.checkoutNemuru(data.nemuruAuthToken, data.nemuruCartHash)
								NEMURU.setStatusCallback(nemuruStatusCallback)

							} else if ('failure' === result.result) {
								throw 'Result failure'
							} else {
								throw 'Invalid response'
							}
						}
						catch (err) {
							// Reload page
							if (true === result.reload) {
								window.location = '';
								return
							}

							// Add new errors
							if (result.messages) {
								nemuru_checkout.submit_error( '<div class="woocommerce-error">' + result.messages + '</div>' );
							}
							else {
								nemuru_checkout.submit_error( '<div class="woocommerce-error">' + wc_checkout_params.i18n_checkout_error + '</div>' );
								// eslint-disable-line max-len
							}
						}
					})
					.fail(function(jqXHR, textStatus, errorThrown){
            nemuru_checkout.submit_error('<div class="woocommerce-error">' + errorThrown + '</div>')
					});

				return false
			},
			send_form: function (data) {
				return $.ajax(data);
			},
			submit_error: function (error_message) {
				$('.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message').remove()
				nemuru_checkout.$checkout_form.prepend('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">' + error_message + '</div>') // eslint-disable-line max-len
				nemuru_checkout.$checkout_form.removeClass('processing').unblock()
				nemuru_checkout.$checkout_form.find('.input-text, select, input:checkbox').trigger('validate').trigger('blur')
				nemuru_checkout.scroll_to_notices()
				$(document.body).trigger('checkout_error', [error_message])
			},
			scroll_to_notices: function () {
				var scrollElement = $('.woocommerce-NoticeGroup-updateOrderReview, .woocommerce-NoticeGroup-checkout')

				if (!scrollElement.length) {
					scrollElement = $('.form.checkout')
				}
				$.scroll_to_notices(scrollElement)
			}
		}
	}
);
