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

	const app = window.MailDoctorAdminApp;

	if (!app) {
		return;
	}

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

	function initDatepickers() {
		if (!$.fn.datepicker) {
			return;
		}

		const selectors = '.mail-doctor-datepicker, #mail-doctor-export-date-from, #mail-doctor-export-date-to';
		$(selectors).each(function () {
			const $input = $(this);
			// Avoid double-initializing but reset stale instances.
			if ($input.hasClass('hasDatepicker')) {
				$input.datepicker('destroy');
			}
			$input.datepicker({
				dateFormat: 'yy-mm-dd',
			});
		});
	}



	function retryLog(logId, $button) {
		if (!ajaxUrl || !logId) {
			return;
		}

		$button.prop('disabled', true);

		$.post(ajaxUrl, {
			action: 'mail_doctor_retry_email',
			_wpnonce: nonces.retry || '',
			log_id: logId,
		})
			.done((response) => {
				if (response && response.success && response.data && response.data.message) {
					window.alert(response.data.message);
					return;
				}

				window.alert(i18n.retrySuccess || 'Retry request queued.');
			})
			.fail(() => {
				window.alert(i18n.retryError || 'Retry failed.');
			})
			.always(() => {
				$button.prop('disabled', false);
			});
	}

	function resendLog(logId, recipient, $button) {
		if (!ajaxUrl || !logId) {
			return;
		}

		$button.prop('disabled', true);

		$.post(ajaxUrl, {
			action: 'mail_doctor_resend_email',
			_wpnonce: nonces.resend || '',
			log_id: logId,
			recipient: recipient || '',
		})
			.done((response) => {
				if (response && response.success) {
					const message =
						(response.data && response.data.message) || i18n.resendSuccess || 'Resend queued.';
					window.alert(message);
					return;
				}

				const errorMessage =
					(response && response.data && response.data.message) || i18n.resendError || 'Unable to queue resend.';
				window.alert(errorMessage);
			})
			.fail(() => {
				window.alert(i18n.resendError || 'Unable to queue resend.');
			})
			.always(() => {
				$button.prop('disabled', false);
			});
	}

	function bindRetryButtons() {
		$document.on('click', '.mail-doctor-retry-log', function (event) {
			event.preventDefault();
			const logId = $(this).data('log-id');
			retryLog(logId, $(this));
		});
	}

	function bindResendButtons() {
		$document.on('click', '.mail-doctor-resend-log', function (event) {
			event.preventDefault();

			const $button = $(this);
			const logId = $button.data('log-id');
			const mode = $button.data('mode');

			if (!logId) {
				return;
			}

			if (mode === 'alternate') {
				const promptMessage = i18n.resendPrompt || 'Send to which email address?';
				const value = window.prompt(promptMessage, '');

				if (value === null) {
					return;
				}

				const recipient = value.trim();

				if (!recipient) {
					window.alert(i18n.resendError || 'Unable to queue resend.');
					return;
				}

				resendLog(logId, recipient, $button);
				return;
			}

			resendLog(logId, '', $button);
		});
	}

	function exportLogs(extraParams) {
		if (!ajaxUrl) {
			return;
		}

		const params = $.param(
			Object.assign(
				{
					action: 'mail_doctor_export_logs',
					_wpnonce: nonces.export || '',
				},
				extraParams
			)
		);

		window.location = `${ajaxUrl}?${params}`;
	}

	function exportLogsAdvanced() {
		if (!adminPostUrl) {
			return;
		}

		const nonce = $('#mail-doctor-export-logs-nonce').val() || '';

		if (!nonce) {
			return;
		}

		const params = {
			action: 'mail_doctor_export_logs_file',
			_mail_doctor_export_logs_nonce: nonce,
			format: $('#mail-doctor-export-format').val() || 'csv',
		};

		const status = $('#mail-doctor-export-status').val();
		const event = $('#mail-doctor-export-event').val();
		const dateFrom = $('#mail-doctor-export-date-from').val();
		const dateTo = $('#mail-doctor-export-date-to').val();
		const includeArchived = $('#mail-doctor-export-include-archived').is(':checked');

		if (status) {
			params.status = status;
		}

		if (event) {
			params.event = event;
		}

		if (dateFrom) {
			params.date_from = dateFrom;
		}

		if (dateTo) {
			params.date_to = dateTo;
		}

		if (includeArchived) {
			params.include_archived = 1;
		}

		window.location = `${adminPostUrl}?${$.param(params)}`;
	}

	function bindExportButtons() {
		$('#mail-doctor-export-logs').on('click', function () {
			const query = $('#mail-doctor-logs-filter')
				.serializeArray()
				.reduce((acc, field) => {
					acc[field.name] = field.value;
					return acc;
				}, {});

			exportLogs(query);
		});

		$('#mail-doctor-export-logs-advanced').on('click', function () {
			exportLogsAdvanced();
		});
	}

	function bindRunQueue() {
		$('#mail-doctor-run-queue-now').on('click', function () {
			if (!ajaxUrl) {
				return;
			}

			const $button = $(this);
			$button.prop('disabled', true);

			$.post(ajaxUrl, {
				action: 'mail_doctor_run_queue_now',
				_wpnonce: nonces.run_queue || '',
			})
				.done((response) => {
					if (response && response.success) {
						const message =
							(response.data && response.data.message) || i18n.runQueueSuccess || 'Queue run triggered.';
						window.alert(message);
						return;
					}

					const errorMessage =
						(response && response.data && response.data.message) || i18n.runQueueError || 'Queue run failed.';
					window.alert(errorMessage);
				})
				.fail(() => {
					window.alert(i18n.runQueueError || 'Queue run failed.');
				})
				.always(() => {
					$button.prop('disabled', false);
				});
		});

		$('#mail-doctor-purge-logs').on('click', function () {
			if (!ajaxUrl) {
				return;
			}

			const message = $(this).data('confirm');
			const $button = $(this);

			if (!window.confirm(message)) {
				return;
			}

			$button.prop('disabled', true);

			$.post(ajaxUrl, {
				action: 'mail_doctor_purge_logs',
				_wpnonce: nonces.purge || '',
			})
				.done((response) => {
					if (response && response.success) {
						const successMessage =
							(response.data && response.data.message) || i18n.purgeSuccess || 'Email logs cleared.';
						window.alert(successMessage);
						return;
					}

					const fallback =
						(response && response.data && response.data.message) || i18n.purgeError || 'Unable to clear email logs.';
					window.alert(fallback);
				})
				.fail(() => {
					window.alert(i18n.purgeError || 'Unable to clear email logs.');
				})
				.always(() => {
					$button.prop('disabled', false);
				});
		});
	}

	function bindCopyButtons() {
		$document.on('click', '.mail-doctor-copy', function () {
			const text = $(this).data('copy') || '';
			const $button = $(this);
			const successLabel = i18n.copied || 'Copied';
			const errorLabel = i18n.copyError || 'Copy failed';

			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard
					.writeText(text)
					.then(() => {
						$button.text(successLabel);
					})
					.catch(() => {
						window.alert(errorLabel);
					});
				return;
			}

			const $temp = $('<textarea/>').css({ position: 'absolute', left: '-9999px', top: '0' }).val(text);
			$('body').append($temp);
			$temp.select();
			try {
				document.execCommand('copy');
				$button.text(successLabel);
			} catch (error) {
				window.alert(errorLabel);
			}
			$temp.remove();
		});
	}

	function bindLogDrawer() {
		const $drawer = $('#mail-doctor-log-drawer');
		const $body = $('#mail-doctor-log-drawer-body');

		if (!$drawer.length) {
			return;
		}

		function openDrawer(logId) {
			$drawer.attr('aria-hidden', 'false').addClass('is-active');
			$('body').addClass('mail-doctor-drawer-open');

			// Show spinner
			$body.html(`
				<div class="mail-doctor-drawer-loading">
					<span class="spinner is-active" style="float: none; margin: 0 auto; display: block;"></span>
					<p>${i18n.loading || 'Loading…'}</p>
				</div>
			`);

			$.post(ajaxUrl, {
				action: 'mail_doctor_get_log_details',
				_wpnonce: nonces.get_log || '',
				log_id: logId
			})
			.done((response) => {
				if (response && response.success && response.data && response.data.html) {
					$body.html(response.data.html);
				} else {
					const errorMsg = (response && response.data && response.data.message) || i18n.previewError || 'Unable to load details.';
					$body.html(`<div class="mail-doctor-drawer-error"><p>${errorMsg}</p></div>`);
				}
			})
			.fail(() => {
				$body.html(`<div class="mail-doctor-drawer-error"><p>${i18n.previewError || 'Unable to load details.'}</p></div>`);
			});
		}

		function closeDrawer() {
			$drawer.attr('aria-hidden', 'true').removeClass('is-active');
			$('body').removeClass('mail-doctor-drawer-open');
			$body.html('');
		}

		$document.on('click', '.mail-doctor-view-log-page', function (event) {
			// Allow standard fallback for middle click or modifier keys
			if (event.ctrlKey || event.metaKey || event.shiftKey || event.button !== 0) {
				return;
			}

			event.preventDefault();
			const logId = $(this).data('log-id');
			if (logId) {
				openDrawer(logId);
			}
		});

		$drawer.on('click', '[data-close-drawer]', function (event) {
			event.preventDefault();
			closeDrawer();
		});

		$(document).on('keydown', function (event) {
			if (event.key === 'Escape' && $drawer.hasClass('is-active')) {
				closeDrawer();
			}
		});
	}

	app.provide('logs', {
	});

	app.register(() => {
		initDatepickers();
		bindRetryButtons();
		bindResendButtons();
		bindExportButtons();
		bindRunQueue();
		bindCopyButtons();
		bindLogDrawer();
	});
})(window, document, jQuery);
