/* global window, document, jQuery */
(function (window, document, $) {
	'use strict';

	const app = window.MailDoctorAdminApp;

	if (!app) {
		return;
	}

	const config = app.config || {};
	const woo = config.woo || {};
	const i18n = app.i18n || {};
	const ajaxUrl = app.ajaxUrl || '';
	const nonces = app.nonces || {};
	const $document = $(document);

	function bindWooPreview() {
		if (!woo.available || !ajaxUrl) {
			return;
		}

		const $emailSelect = $('#mail-doctor-preview-email');
		const $orderInput = $('#mail-doctor-preview-order');
		const $hiddenEmail = $('#mail-doctor-preview-email-setting');
		const $hiddenOrder = $('#mail-doctor-preview-order-setting');
		const $status = $('.mail-doctor-woo-preview__status');
		const $output = $('.mail-doctor-woo-preview__output');

		function setStatus(message, type) {
			if (!$status.length) {
				return;
			}

			const stateClass = type ? `is-${type}` : '';
			$status.removeClass('is-error is-success is-loading');
			if (stateClass) {
				$status.addClass(stateClass);
			}
			$status.text(message || '');
		}

		function syncHidden() {
			if ($hiddenEmail.length) {
				$hiddenEmail.val($emailSelect.val() || '');
			}
			if ($hiddenOrder.length) {
				$hiddenOrder.val($orderInput.val() || '');
			}
		}

		$emailSelect.on('change', function () {
			syncHidden();
			setStatus('');
		});

		$orderInput.on('input', syncHidden);

		$document.on('click', '.mail-doctor-preview-action', function (event) {
			event.preventDefault();

			const $button = $(this);
			const mode = $button.data('mode');
			const emailId = ($emailSelect.val() || '').toString();
			const orderId = parseInt($orderInput.val(), 10) || '';

			if (!emailId) {
				const selectMessage = i18n.previewSelect || 'Select an email template first.';
				setStatus(selectMessage, 'error');
				return;
			}

			const action = mode === 'send' ? 'mail_doctor_send_preview_woo_email' : 'mail_doctor_preview_woo_email';
			const nonceKey = mode === 'send' ? 'previewSend' : 'preview';
			const loadingMessage =
				mode === 'send'
					? i18n.sending || 'Sending…'
					: i18n.previewLoading || 'Rendering…';

			const disableSet = $button.closest('.mail-doctor-woo-preview__controls').find('.mail-doctor-preview-action');
			disableSet.prop('disabled', true);
			setStatus(loadingMessage, 'loading');

			const payload = {
				action,
				_wpnonce: nonces[nonceKey] || '',
				email: emailId,
				order_id: orderId,
			};

			$.post(ajaxUrl, payload)
				.done((response) => {
					if (!response || !response.success) {
						const message =
							(response && response.data && response.data.message) ||
							i18n.previewError ||
							'Preview failed.';
						setStatus(message, 'error');
						return;
					}

					const data = response.data || {};

					if (data.orderId) {
						$orderInput.val(data.orderId);
						syncHidden();
					}

					if (data.html && $output.length) {
						$output.html(data.html);
					} else if ($output.length) {
						$output.empty();
					}

					if (mode === 'send') {
						const sentMessage = i18n.previewSent || 'Preview email sent.';
						const recipient = data.sentTo ? ` ${data.sentTo}` : '';
						setStatus(sentMessage + recipient, 'success');
					} else {
						const readyMessage = i18n.previewReady || 'Preview generated.';
						setStatus(readyMessage, 'success');
					}
				})
				.fail((jqXHR) => {
					let message = i18n.previewError || 'Preview failed.';
					if (jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.data && jqXHR.responseJSON.data.message) {
						message = jqXHR.responseJSON.data.message;
					}
					setStatus(message, 'error');
				})
				.always(() => {
					disableSet.prop('disabled', false);
				});
		});

		syncHidden();
	}

	app.register(bindWooPreview);
})(window, document, jQuery);
