/**
 * Alsendo Connect - Sender Templates management.
 *
 * @package Inspire_Labs\Alsendo_Connect
 */

var alsendoSenderDialog;
var alsendoSenderTrTemplate;
var alsendoSenderFields = [
	'id', 'name', 'is_residential', 'country', 'company_name',
	'first_name', 'last_name', 'street', 'building_number', 'apartment_number',
	'block', 'entrance', 'floor',
	'postal_code', 'province', 'city', 'contact_person', 'phone', 'email',
	'bank_account_number'
];

var alsendoSenderSelectFields = ['is_residential', 'country'];

var alsendoSenderIsSaving = false;

const alsendoSenderShowPageNotice = function (type, message) {
	jQuery('#wpbody .wp-header-end').after(
		'<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>'
	);
};

const alsendoSenderShowDialogMessage = function (message, type) {
	type = type || 'error';
	var bgColor = type === 'success' ? '#ecf7ed' : '#fcf0f1';
	var borderColor = type === 'success' ? '#00a32a' : '#d63638';
	var textColor = type === 'success' ? '#00a32a' : '#d63638';

	var $msgBox = jQuery('#alsendo-stpl-dialog-message');
	if (!$msgBox.length) {
		jQuery('#alsendoSenderTemplateFormFields').append(
			'<div id="alsendo-stpl-dialog-message"></div>'
		);
		$msgBox = jQuery('#alsendo-stpl-dialog-message');
	}
	$msgBox
		.css({
			'margin-top': '12px',
			'padding': '8px 12px',
			'background': bgColor,
			'border-left': '4px solid ' + borderColor,
			'color': textColor,
			'font-size': '13px'
		})
		.html(message).show();
};

const alsendoSenderClearDialogMessages = function () {
	jQuery('#alsendo-stpl-dialog-message').hide().html('');
};

const alsendoSenderSetSavingState = function (isSaving) {
	alsendoSenderIsSaving = isSaving;
	var $saveBtn = alsendoSenderDialog.closest('.ui-dialog').find('.ui-dialog-buttonpane button').first();

	if (isSaving) {
		$saveBtn.prop('disabled', true).css('opacity', '0.6');
		if (!$saveBtn.find('.alsendo-spinner').length) {
			$saveBtn.prepend('<span class="alsendo-spinner"></span>');
		}
	} else {
		$saveBtn.prop('disabled', false).css('opacity', '1');
		$saveBtn.find('.alsendo-spinner').remove();
	}
};

const alsendoSenderSafeReload = function () {
	window.onbeforeunload = null;
	jQuery(window).off('beforeunload');
	window.location.reload();
};

const alsendoSenderShowRowSpinner = function ($btn) {
	var $tr = $btn.closest('tr');
	$tr.find('.button').prop('disabled', true).css('opacity', '0.6');
	$btn.after('<span class="spinner is-active" style="float:none;margin:0 0 0 4px;"></span>');
};

const alsendoSenderOnClickAdd = function () {
	alsendoSenderClearDialogMessages();
	alsendoSenderDialog.dialog('option', 'title', alsendo_connect_sender_templates.i18n_add_template);
	alsendoSenderOpenDialog();
};

const alsendoSenderOnClickEdit = function () {
	alsendoSenderClearDialogMessages();
	alsendoSenderDialog.dialog('option', 'title', alsendo_connect_sender_templates.i18n_edit_template);
	alsendoSenderTrTemplate = jQuery(this).parentsUntil('tbody', 'tr').get(0);
	alsendoSenderOpenDialog();
};

const alsendoSenderOnClickDelete = function () {
	alsendoSenderTrTemplate = jQuery(this).parentsUntil('tbody', 'tr').get(0);
	if (undefined !== alsendoSenderTrTemplate) {
		var template = jQuery(alsendoSenderTrTemplate).data('template') || '';
		var id = template['id'] || 0;
		if (0 === id) {
			return;
		}

		if (true === alsendoSenderIsSaving) {
			return;
		}
		alsendoSenderIsSaving = true;

		var $deleteBtn = jQuery(this);
		alsendoSenderShowRowSpinner($deleteBtn);

		var data = {
			action: 'alsendo_connect_sender_template_delete',
			'template_delete': {
				_nonce: template._nonce,
				id: template.id,
				_legacy_slug: template._legacy_slug || ''
			}
		};

		console.log('[Alsendo Sender Templates] Delete request:', data);

		jQuery.post({
			url: alsendo_connect_sender_templates.ajax_url,
			dataType: 'json',
			data: data
		})
			.done(function () {
				console.log('[Alsendo Sender Templates] Delete success');
				alsendoSenderSafeReload();
			})
			.fail(function (xhr) {
				console.error('[Alsendo Sender Templates] Delete failed:', xhr.status, xhr.responseText);
				alsendoSenderShowPageNotice('error', alsendo_connect_sender_templates.i18n_error_deleting + ' (HTTP ' + xhr.status + ')');
				var $tr = $deleteBtn.closest('tr');
				$tr.find('.spinner').remove();
				$tr.find('.button').prop('disabled', false).css('opacity', '1');
			})
			.always(function () {
				jQuery("html, body").scrollTop(0);
				alsendoSenderIsSaving = false;
			});
	}
};

const alsendoSenderOnClickSetDefault = function () {
	var $btn = jQuery(this);

	if ($btn.hasClass('is-default') || $btn.prop('disabled')) {
		return;
	}

	if (true === alsendoSenderIsSaving) {
		return;
	}
	alsendoSenderIsSaving = true;

	var slug = $btn.data('slug');
	alsendoSenderShowRowSpinner($btn);

	jQuery.ajax({
		url: alsendo_connect_sender_templates.ajax_url,
		type: 'POST',
		dataType: 'json',
		data: {
			action: 'alsendo_connect_sender_template_set_default',
			_nonce: alsendo_connect_sender_templates.set_default_nonce,
			template_slug: slug
		}
	})
		.done(function () {
			console.log('[Alsendo Sender Templates] Default template updated to:', slug);
			alsendoSenderSafeReload();
		})
		.fail(function (xhr) {
			console.error('[Alsendo Sender Templates] Set default failed:', xhr.status, xhr.responseText);
			alsendoSenderShowPageNotice('error', alsendo_connect_sender_templates.i18n_error_setting_default + ' (HTTP ' + xhr.status + ')');
			var $tr = $btn.closest('tr');
			$tr.find('.spinner').remove();
			$tr.find('.button').prop('disabled', false).css('opacity', '1');
		})
		.always(function () {
			alsendoSenderIsSaving = false;
		});
};

const alsendoSenderOpenDialog = function () {
	var $checkbox = jQuery('#alsendo_sender_set_as_default');
	if ($checkbox.length) {
		$checkbox.prop('checked', false);
	}

	if (undefined !== alsendoSenderTrTemplate) {
		var template = jQuery(alsendoSenderTrTemplate).data('template') || '';

		jQuery.each(alsendoSenderFields, function (i, el) {
			var $field = jQuery('#alsendo_sender_template_' + el);

			if (alsendoSenderSelectFields.indexOf(el) !== -1) {
				$field.val(template[el] || '').change();
			} else {
				$field.val(template[el] || '');
			}
		});

		var legacySlug = template['_legacy_slug'] || '';
		jQuery('#alsendo_sender_template_legacy_slug').val(legacySlug);

		var templateSlug = template['template_slug'] || '';
		if (templateSlug && templateSlug === alsendo_connect_sender_templates.default_slug) {
			if ($checkbox.length) {
				$checkbox.prop('checked', true);
			}
		}
	}
	alsendoSenderDialog.dialog('open');
};

const alsendoSenderResetForm = function () {
	alsendoSenderTrTemplate = undefined;

	jQuery.each(alsendoSenderFields, function (i, el) {
		var $field = jQuery('#alsendo_sender_template_' + el);

		if (alsendoSenderSelectFields.indexOf(el) !== -1) {
			$field.prop('selectedIndex', 0).change();
		} else {
			$field.val('');
		}
	});

	jQuery('#alsendo_sender_template_legacy_slug').val('');

	var $checkbox = jQuery('#alsendo_sender_set_as_default');
	if ($checkbox.length) {
		$checkbox.prop('checked', false);
	}

	alsendoSenderClearDialogMessages();
};

const alsendoSenderValidateForm = function () {
	var errors = [];

	var name = jQuery('#alsendo_sender_template_name').val().trim();
	if (!name) {
		errors.push(alsendo_connect_sender_templates.i18n_field_template_name);
	}

	return errors;
};

const alsendoSenderSaveTemplate = function () {
	if (true === alsendoSenderIsSaving) {
		console.log('[Alsendo Sender Templates] Save blocked - already saving');
		return;
	}

	alsendoSenderClearDialogMessages();

	var validationErrors = alsendoSenderValidateForm();
	if (validationErrors.length > 0) {
		alsendoSenderShowDialogMessage(
			alsendo_connect_sender_templates.i18n_fill_required + ' <strong>' + validationErrors.join(', ') + '</strong>',
			'error'
		);
		return;
	}

	alsendoSenderSetSavingState(true);

	var serializedData = jQuery('#alsendoSenderTemplateDialog :input').serializeArray();

	var setAsDefault = jQuery('#alsendo_sender_set_as_default').is(':checked') ? '1' : '0';
	serializedData.push({ name: 'template[set_as_default]', value: setAsDefault });

	console.log('[Alsendo Sender Templates] Save button clicked');
	console.log('[Alsendo Sender Templates] AJAX URL:', alsendo_connect_sender_templates.ajax_url);
	console.log('[Alsendo Sender Templates] Serialized payload:', serializedData);

	var dataObj = {};
	jQuery.each(serializedData, function(i, field) {
		dataObj[field.name] = field.value;
	});
	console.log('[Alsendo Sender Templates] Payload as object:', dataObj);

	jQuery.ajax({
		url: alsendo_connect_sender_templates.ajax_url,
		type: 'POST',
		dataType: 'json',
		data: serializedData
	})
		.done(function (response, textStatus, xhr) {
			console.log('[Alsendo Sender Templates] Save success:', xhr.status, response);
			alsendoSenderSetSavingState(false);
			alsendoSenderShowDialogMessage(alsendo_connect_sender_templates.i18n_saved, 'success');

			setTimeout(function () {
				alsendoSenderSafeReload();
			}, 300);
		})
		.fail(function (xhr) {
			console.error('[Alsendo Sender Templates] Save failed:', xhr.status, xhr.statusText);
			console.error('[Alsendo Sender Templates] Response body:', xhr.responseText);

			var errorMsg = '';

			if (xhr.responseJSON) {
				console.log('[Alsendo Sender Templates] Response JSON:', xhr.responseJSON);
				if (Array.isArray(xhr.responseJSON)) {
					jQuery.each(xhr.responseJSON, function (index, element) {
						if ('string' === typeof element || element instanceof String) {
							errorMsg += element + '<br>';
						} else if (element.message) {
							errorMsg += element.message + '<br>';
						}
					});
				} else if (typeof xhr.responseJSON === 'object' && xhr.responseJSON.message) {
					errorMsg = xhr.responseJSON.message;
				}
			}

			if (!errorMsg) {
				if (xhr.responseText === '0') {
					errorMsg = alsendo_connect_sender_templates.i18n_ajax_not_found;
				} else {
					errorMsg = alsendo_connect_sender_templates.i18n_server_error + ' (HTTP ' + xhr.status + ')';
				}
			}

			alsendoSenderShowDialogMessage(errorMsg, 'error');
			alsendoSenderSetSavingState(false);
		});
};

jQuery(document).ready(function ($) {

	console.log('[Alsendo Sender Templates] Initializing...');
	console.log('[Alsendo Sender Templates] Config:', typeof alsendo_connect_sender_templates !== 'undefined' ? alsendo_connect_sender_templates : 'NOT LOADED');

	if (!$('#alsendoSenderTemplateDialog').length) {
		console.warn('[Alsendo Sender Templates] Dialog element #alsendoSenderTemplateDialog not found');
		return;
	}

	var alsendoSenderCSS = document.createElement('style');
	alsendoSenderCSS.textContent =
		'@keyframes alsendo-spin { to { transform: rotate(360deg); } }' +
		'.alsendo-spinner {' +
		'  display:inline-block;width:14px;height:14px;' +
		'  border:2px solid #ccc;border-top-color:#0073aa;' +
		'  border-radius:50%;animation:alsendo-spin .6s linear infinite;' +
		'  margin-right:6px;vertical-align:middle;' +
		'}' +
		'.ui-dialog[aria-describedby="alsendoSenderTemplateDialog"] .ui-dialog-titlebar-close {' +
		'  display:none !important;' +
		'}' +
		'.alsendo-stpl-default-checkbox-row {' +
		'  display:flex;align-items:center;gap:6px;' +
		'  padding:8px 16px 0;font-size:13px;' +
		'}' +
		'.alsendo-stpl-default-checkbox-row input[type="checkbox"] {' +
		'  margin:0;' +
		'}' +
		'.alsendo-stpl-default-checkbox-row label {' +
		'  cursor:pointer;user-select:none;' +
		'}';
	document.head.appendChild(alsendoSenderCSS);

	alsendoSenderDialog = $('#alsendoSenderTemplateDialog').dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: 680,
		position: { my: 'center top', at: 'center top+70', of: window },
		buttons: {
			Save: {
				text: alsendo_connect_sender_templates.i18n_save,
				click: alsendoSenderSaveTemplate,
				class: 'button button-primary'
			},
			Cancel: {
				text: alsendo_connect_sender_templates.i18n_cancel,
				click: function () {
					alsendoSenderDialog.dialog("close");
				},
				class: 'button'
			}
		},
		open: function () {
			alsendoSenderDialog.dialog('option', 'position', { my: 'center top', at: 'center top+70', of: window });
		},
		close: function () {
			alsendoSenderResetForm();
		}
	});

	var $buttonPane = alsendoSenderDialog.closest('.ui-dialog').find('.ui-dialog-buttonpane');
	if ($buttonPane.length) {
		$buttonPane.prepend(
			'<div class="alsendo-stpl-default-checkbox-row">' +
			'<input type="checkbox" id="alsendo_sender_set_as_default" value="1">' +
			'<label for="alsendo_sender_set_as_default">' + alsendo_connect_sender_templates.i18n_set_as_default + '</label>' +
			'</div>'
		);
	}

	$('#alsendo_connect_add_sender_template').on('click', alsendoSenderOnClickAdd);
	$('body').on('click', '.alsendo_connect_edit_sender_template', alsendoSenderOnClickEdit);
	$('body').on('click', '.alsendo_connect_delete_sender_template', alsendoSenderOnClickDelete);
	$('body').on('click', '.alsendo_connect_set_default_sender_template:not(.is-default)', alsendoSenderOnClickSetDefault);

	console.log('[Alsendo Sender Templates] Ready.');
});
