/* 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 openModal(data, emlUrl) {
		const $modal = $('#mail-doctor-log-modal');

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

		Object.keys(data || {}).forEach((key) => {
			$modal.find(`[data-field="${key}"]`).text(data[key] || '—');
		});

		// Wire up the EML download link (URL passed separately to avoid JSON/esc_attr issues).
		const $emlLink = $modal.find('#mail-doctor-eml-download-link');
		if ($emlLink.length) {
			if (emlUrl) {
				$emlLink.attr('href', emlUrl).removeClass('mail-doctor-hidden');
			} else {
				$emlLink.addClass('mail-doctor-hidden').attr('href', '#');
			}
		}

		$modal.removeClass('mail-doctor-hidden');
		document.body.classList.add('mail-doctor-modal-open');
		const $close = $modal.find('[data-dismiss]').first();
		if ($close.length) {
			$close.trigger('focus');
		}

		$modal.on('keydown.mdModal', (event) => {
			if (event.key === 'Escape') {
				closeModal();
			}
		});
	}

	function closeModal() {
		const $modal = $('#mail-doctor-log-modal');
		$modal.addClass('mail-doctor-hidden');
		$modal.off('keydown.mdModal');
		document.body.classList.remove('mail-doctor-modal-open');
	}

	function bindModal() {
		$document.on('click', '.mail-doctor-view-log', function () {
			const json = $(this).attr('data-log');
			const emlUrl = $(this).attr('data-eml-url') || '';

			if (!json) {
				return;
			}

			try {
				const data = JSON.parse(json);
				openModal(data, emlUrl);
			} catch (error) {
				if (window.console && typeof window.console.error === 'function') {
					window.console.error(error);
				}
			}
		});

		$document.on('click', '#mail-doctor-log-modal [data-dismiss]', closeModal);
		$document.on('click', '#mail-doctor-log-modal .mail-doctor-modal__overlay', closeModal);
	}

	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();
		});
	}

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

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