/* eslint-disable */
/* global _MASTERIYO_CHECKOUT_ */

jQuery(function ($) {
	// Bail if the global checkout parameters doesn't exits.
	if (typeof _MASTERIYO_CHECKOUT_ === 'undefined') {
		return false;
	}

	function getSpinner() {
		return '<span class="spinner" style="visibility:visible"></span>';
	}

	function getBlockLoadingConfiguration() {
		return {
			message: getSpinner(),
			css: {
				border: '',
				width: '0%',
			},
			overlayCSS: {
				background: '#fff',
				opacity: 0.6,
			},
		};
	}

	var checkoutForm = {
		$form: $('form.masteriyo-checkout'),

		init: function () {
			// Apply coupon.
			this.$form.on(
				'click',
				'.masteriyo-apply-coupon-btn',
				this.applyCouponHandler
			);

			// Remove coupon.
			this.$form.on(
				'click',
				'.masteriyo-remove-coupon',
				this.removeCouponHandler
			);
		},

		getAjaxURL: function () {
			return _MASTERIYO_CHECKOUT_.ajaxURL;
		},

		getCheckoutURL: function () {
			return _MASTERIYO_CHECKOUT_.checkoutURL;
		},

		removeErrorNotices: function () {
			$(
				'.masteriyo-NoticeGroup-checkout, .masteriyo-error, .masteriyo-message'
			).remove();
		},

		/**
		 * Display error message.
		 */
		showError: function (errorMessage) {
			checkoutForm.$form.prepend(
				'<div class="masteriyo-NoticeGroup masteriyo-NoticeGroup-checkout">' +
					errorMessage +
					'</div>'
			); // eslint-disable-line max-len

			checkoutForm.$form
				.find('.input-text, select, input:checkbox')
				.trigger('validate')
				.trigger('blur');

			checkoutForm.scrollToNotices();

			$(document.body).trigger('checkout_error', [errorMessage]);
		},

		/**
		 * Scroll to notices.
		 */
		scrollToNotices: function () {
			var scrollElement = $(
				'.masteriyo-NoticeGroup-updateOrderReview, .masteriyo-NoticeGroup-checkout'
			);

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

			if (scrollElement.length) {
				$('html, body').animate(
					{
						scrollTop: scrollElement.offset().top - 100,
					},
					1000
				);
			}
		},

		/**
		 * Handle apply-coupon action.
		 */
		applyCouponHandler: function (event) {
			event.preventDefault();

			var coupon = $('#masteriyo-coupon-input').val().trim();

			if (!coupon || checkoutForm.$form.is('.processing')) {
				return;
			}

			$.ajax({
				type: 'POST',
				url: checkoutForm.getAjaxURL(),
				dataType: 'json',
				data: {
					action: 'masteriyo_apply_coupon',
					_wpnonce: $('[name="masteriyo-apply-coupon-nonce"]').val(),
					coupon: coupon,
				},
				beforeSend: function (jqXHR) {
					checkoutForm.removeErrorNotices();
					checkoutForm.$form.block(getBlockLoadingConfiguration());
				},
				success: function (response, textStatus, jqXHR) {
					if (response.success) {
						$.each(response.data.fragments, function (key, value) {
							if (
								!checkoutForm.fragments ||
								checkoutForm.fragments[key] !== value
							) {
								$(key).replaceWith(value);
							}
						});
						checkoutForm.fragments = response.data.fragments;

						$('#masteriyo-coupon-input').val('');
					} else {
						checkoutForm.showError(
							'<div class="masteriyo-error">' + response.data.message + '</div>'
						);
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					try {
						var error = jqXHR.responseJSON;
						checkoutForm.showError(
							'<div class="masteriyo-error">' + error.data.messages + '</div>'
						);
					} catch (error) {
						console.log(error);
					}
				},
				complete: function (jqXHR, textStatus) {
					checkoutForm.$form.unblock();
				},
			});
		},

		/**
		 * Handle remove coupon action.
		 */
		removeCouponHandler: function (event) {
			event.preventDefault();

			var coupon = $(event.currentTarget).data('coupon-code');

			if (!coupon || checkoutForm.$form.is('.processing')) {
				return;
			}

			$.ajax({
				type: 'POST',
				url: checkoutForm.getAjaxURL(),
				dataType: 'json',
				data: {
					action: 'masteriyo_remove_applied_coupon',
					_wpnonce: $('[name="masteriyo-remove-applied-coupon-nonce"]').val(),
					coupon: coupon,
				},
				beforeSend: function (jqXHR) {
					checkoutForm.removeErrorNotices();
					checkoutForm.$form.block(getBlockLoadingConfiguration());
				},
				success: function (response, textStatus, jqXHR) {
					if (response.success) {
						$.each(response.data.fragments, function (key, value) {
							if (
								!checkoutForm.fragments ||
								checkoutForm.fragments[key] !== value
							) {
								$(key).replaceWith(value);
							}
						});
						checkoutForm.fragments = response.data.fragments;
					} else {
						checkoutForm.showError(
							'<div class="masteriyo-error">' + response.data.message + '</div>'
						);
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					try {
						var error = jqXHR.responseJSON;
						checkoutForm.showError(
							'<div class="masteriyo-error">' + error.data.messages + '</div>'
						);
					} catch (error) {
						console.log(error);
					}
				},
				complete: function (jqXHR, textStatus) {
					checkoutForm.$form.unblock();
				},
			});
		},
	};

	checkoutForm.init();
});
