(function (window, $) {
	'use strict';

	const app = window.WPMDEmailTemplatesApp;

	if (!app) {
		return;
	}

	function withButtonState($button, promiseFactory) {
		if (!$button || !$button.length) {
			return;
		}

		$button.prop('disabled', true).addClass('updating-message');

		promiseFactory()
			.always(function () {
				$button.prop('disabled', false).removeClass('updating-message');
			});
	}

	app.register(() => {
		const formService = app.resolve('form');
		const notices = app.resolve('notices');
		const modal = app.resolve('modal');

		if (!formService) {
			return;
		}

		function handlePreview(event) {
			event.preventDefault();
			notices && notices.clear();

			const payload = formService.getTemplatePayload();
			const ajaxUrl = app.getAjaxUrl();

			if (!ajaxUrl) {
				window.alert('Ajax URL not available. Please refresh the page.');
				return;
			}

			const request = {
				action: 'wpmd_preview_template',
				nonce: app.config.nonces ? app.config.nonces.preview : '',
				email_type: formService.getEmailType(),
				order_id: $('#wpmd-test-order').val(),
				template: payload,
			};

			const $button = $(event.currentTarget);

			if (notices) {
				const previewing = app.config.i18n && app.config.i18n.previewing ? app.config.i18n.previewing : 'Rendering preview…';
				notices.show(previewing);
			}

			withButtonState($button, function () {
				return $.post(ajaxUrl, request)
					.done(function (response) {
						if (response && response.success && response.data && response.data.html) {
							modal && modal.open(response.data.html);

							if (notices) {
								const message = app.config.i18n && app.config.i18n.previewing ? app.config.i18n.previewing.replace('…', ' complete.') : 'Preview ready.';
								notices.show(message);
							}
						} else {
							window.alert(app.config.i18n && app.config.i18n.saveError ? app.config.i18n.saveError : 'Unable to render preview.');
						}
					})
					.fail(function () {
						window.alert(app.config.i18n && app.config.i18n.saveError ? app.config.i18n.saveError : 'Unable to render preview.');
					});
			});
		}

		function handleSendTest(event) {
			event.preventDefault();
			notices && notices.clear();

			const recipient = $('#wpmd-test-recipient').val();

			if (!recipient) {
				window.alert(app.config.i18n && app.config.i18n.sendError ? app.config.i18n.sendError : 'Please provide a recipient email.');
				return;
			}

			const payload = formService.getTemplatePayload();
			const ajaxUrl = app.getAjaxUrl();

			if (!ajaxUrl) {
				window.alert('Ajax URL not available. Please refresh the page.');
				return;
			}

			const request = {
				action: 'wpmd_send_test',
				nonce: app.config.nonces ? app.config.nonces.send : '',
				email_type: formService.getEmailType(),
				order_id: $('#wpmd-test-order').val(),
				recipient: recipient,
				template: payload,
			};

			const $button = $(event.currentTarget);

			if (notices) {
				const sending = app.config.i18n && app.config.i18n.sending ? app.config.i18n.sending : 'Sending…';
				notices.show(sending);
			}

			withButtonState($button, function () {
				return $.post(ajaxUrl, request)
					.done(function (response) {
						if (response && response.success) {
							window.alert(app.config.i18n && app.config.i18n.sendSuccess ? app.config.i18n.sendSuccess : 'Test email sent.');
						} else {
							const fallback =
								(response && response.data && response.data.message) ||
								(app.config.i18n && app.config.i18n.sendError ? app.config.i18n.sendError : 'Unable to send test email.');
							window.alert(fallback);
						}
					})
					.fail(function () {
						window.alert(app.config.i18n && app.config.i18n.sendError ? app.config.i18n.sendError : 'Unable to send test email.');
					});
			});
		}

		$(document).on('click', '.wpmd-preview-button', handlePreview);
		$(document).on('click', '.wpmd-send-test-button', handleSendTest);
	});
})(window, jQuery);
