/**
 * Admin Data Export/Import JavaScript
 *
 * Handles tab switching, file upload validation, select all/none,
 * and AJAX import with progress updates.
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/assets/js
 * @since      1.0.265
 */

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

	/**
	 * Data Admin Module
	 */
	var MACMDataAdmin = {
		/**
		 * Initialize the module.
		 */
		init: function() {
			this.bindEvents();
			this.initFileUpload();
		},

		/**
		 * Bind event handlers.
		 */
		bindEvents: function() {
			// Select all/none buttons.
			$('.macm-select-all').on('click', this.selectAll);
			$('.macm-select-none').on('click', this.selectNone);

			// Export form validation.
			$('.macm-export-form').on('submit', this.validateExport);

			// Import form handling.
			$('#macm-import-form').on('submit', this.handleImport.bind(this));

			// File input change.
			$('#macm-import-file').on('change', this.handleFileSelect.bind(this));

			// Reset button.
			$('#macm-reset-btn').on('click', this.handleReset.bind(this));
		},

		/**
		 * Initialize file upload drag and drop.
		 */
		initFileUpload: function() {
			var $upload = $('.macm-file-upload');

			$upload.on('dragover dragenter', function(e) {
				e.preventDefault();
				e.stopPropagation();
				$(this).addClass('dragover');
			});

			$upload.on('dragleave dragend drop', function(e) {
				e.preventDefault();
				e.stopPropagation();
				$(this).removeClass('dragover');
			});

			$upload.on('drop', function(e) {
				var files = e.originalEvent.dataTransfer.files;
				if (files.length) {
					$('#macm-import-file')[0].files = files;
					$('#macm-import-file').trigger('change');
				}
			});
		},

		/**
		 * Select all checkboxes.
		 *
		 * @param {Event} e Click event.
		 */
		selectAll: function(e) {
			e.preventDefault();
			$('.macm-entity-card input[type="checkbox"]:not(:disabled)').prop('checked', true);
		},

		/**
		 * Deselect all checkboxes.
		 *
		 * @param {Event} e Click event.
		 */
		selectNone: function(e) {
			e.preventDefault();
			$('.macm-entity-card input[type="checkbox"]').prop('checked', false);
		},

		/**
		 * Validate export form.
		 *
		 * @param {Event} e Submit event.
		 * @return {boolean} Whether form is valid.
		 */
		validateExport: function(e) {
			var $checked = $('.macm-entity-card input[type="checkbox"]:checked');

			if ($checked.length === 0) {
				e.preventDefault();
				alert(macmDataAdmin.i18n.selectDataType || 'Please select at least one data type to export.');
				return false;
			}

			return true;
		},

		/**
		 * Handle file selection.
		 *
		 * @param {Event} e Change event.
		 */
		handleFileSelect: function(e) {
			var file = e.target.files[0];
			var $preview = $('#macm-file-preview');

			// Reset import state when new file is selected.
			this.importId = null;
			$('#macm-import-btn').html('<span class="dashicons dashicons-upload"></span> Start Import');
			$('#macm-import-results').hide();
			$('#macm-import-progress').hide();

			if (!file) {
				$preview.hide();
				return;
			}

			// Validate file type.
			var validTypes = ['application/json', 'text/csv', 'text/plain'];
			var validExtensions = ['.json', '.csv'];
			var fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));

			if (validTypes.indexOf(file.type) === -1 && validExtensions.indexOf(fileExtension) === -1) {
				alert(macmDataAdmin.i18n.invalidFileType);
				e.target.value = '';
				$preview.hide();
				return;
			}

			// Validate file size (10MB max).
			var maxSize = 10 * 1024 * 1024;
			if (file.size > maxSize) {
				alert(macmDataAdmin.i18n.fileTooLarge);
				e.target.value = '';
				$preview.hide();
				return;
			}

			// Update file label.
			$('.macm-file-text').text(file.name + ' (' + this.formatFileSize(file.size) + ')');

			// Show preview for JSON files.
			if (fileExtension === '.json') {
				this.previewJsonFile(file, $preview);
			} else {
				this.previewCsvFile(file, $preview);
			}
		},

		/**
		 * Preview JSON file contents.
		 *
		 * @param {File}   file     The file to preview.
		 * @param {jQuery} $preview The preview container.
		 */
		previewJsonFile: function(file, $preview) {
			var reader = new FileReader();
			var self = this;

			reader.onload = function(e) {
				try {
					var data = JSON.parse(e.target.result);
					var html = '';

					if (data.macm_export) {
						html += '<div class="macm-preview-item">';
						html += '<span>Export Version:</span>';
						html += '<span>' + self.escapeHtml(data.macm_export.version || 'Unknown') + '</span>';
						html += '</div>';

						html += '<div class="macm-preview-item">';
						html += '<span>Export Date:</span>';
						html += '<span>' + self.escapeHtml(data.macm_export.exported_at || 'Unknown') + '</span>';
						html += '</div>';

						if (data.macm_export.entities_included) {
							html += '<div class="macm-preview-item">';
							html += '<span>Entities:</span>';
							html += '<span>' + self.escapeHtml(data.macm_export.entities_included.join(', ')) + '</span>';
							html += '</div>';
						}
					}

					// Count records per entity.
					var counts = [];
					for (var key in data) {
						if (key !== 'macm_export' && Array.isArray(data[key])) {
							counts.push(key + ': ' + data[key].length);
						}
					}

					if (counts.length) {
						html += '<div class="macm-preview-item">';
						html += '<span>Records:</span>';
						html += '<span>' + self.escapeHtml(counts.join(', ')) + '</span>';
						html += '</div>';
					}

					$preview.find('.macm-preview-content').html(html);
					$preview.show();
				} catch (err) {
					$preview.find('.macm-preview-content').html('<p>Unable to parse JSON file.</p>');
					$preview.show();
				}
			};

			reader.readAsText(file);
		},

		/**
		 * Preview CSV file contents.
		 *
		 * @param {File}   file     The file to preview.
		 * @param {jQuery} $preview The preview container.
		 */
		previewCsvFile: function(file, $preview) {
			var reader = new FileReader();
			var self = this;

			reader.onload = function(e) {
				var lines = e.target.result.split('\n');
				var html = '';

				html += '<div class="macm-preview-item">';
				html += '<span>Total Rows:</span>';
				html += '<span>' + (lines.length - 1) + ' (excluding header)</span>';
				html += '</div>';

				if (lines.length > 0) {
					var headers = lines[0].split(',');
					html += '<div class="macm-preview-item">';
					html += '<span>Columns:</span>';
					html += '<span>' + self.escapeHtml(headers.join(', ')) + '</span>';
					html += '</div>';
				}

				$preview.find('.macm-preview-content').html(html);
				$preview.show();
			};

			reader.readAsText(file);
		},

		/**
		 * Current import ID (set after validation).
		 */
		importId: null,

		/**
		 * Handle import form submission.
		 *
		 * Two-step process: validate first, then import.
		 *
		 * @param {Event} e Submit event.
		 */
		handleImport: function(e) {
			e.preventDefault();

			var $form = $(e.target);
			var $file = $('#macm-import-file');

			// Validate file selection.
			if (!$file[0].files.length) {
				alert(macmDataAdmin.i18n.selectFile);
				return;
			}

			// If we already have an import_id, proceed with import.
			if (this.importId) {
				this.executeImport($form);
				return;
			}

			// Show progress section.
			$('#macm-import-progress').show();
			$('#macm-import-results').hide();
			$('#macm-import-btn').prop('disabled', true);
			this.updateProgress(10, 'Validating file...');

			// Prepare form data for validation.
			var formData = new FormData($form[0]);
			formData.append('action', 'macm_validate_import');
			formData.append('nonce', macmDataAdmin.nonce);

			// First step: validate the file.
			this.validateImport(formData, $form);
		},

		/**
		 * Step 1: Validate import file via AJAX.
		 *
		 * @param {FormData} formData The form data.
		 * @param {jQuery}   $form    The form element.
		 */
		validateImport: function(formData, $form) {
			var self = this;

			$.ajax({
				url: macmDataAdmin.ajaxUrl,
				type: 'POST',
				data: formData,
				processData: false,
				contentType: false,
				success: function(response) {
					if (response.success) {
						// Store import_id and show preview.
						self.importId = response.data.import_id;
						self.updateProgress(30, 'File validated. Review preview and confirm import...');
						self.showValidationPreview(response.data);

						// Now wait for user to confirm.
						$('#macm-import-btn').prop('disabled', false).html(
							'<span class="dashicons dashicons-yes"></span> Confirm Import'
						);
					} else {
						self.showError(response.data.message || macmDataAdmin.i18n.error);
						$('#macm-import-btn').prop('disabled', false).html(
							'<span class="dashicons dashicons-upload"></span> Start Import'
						);
					}
				},
				error: function() {
					self.showError(macmDataAdmin.i18n.error);
					$('#macm-import-btn').prop('disabled', false).html(
						'<span class="dashicons dashicons-upload"></span> Start Import'
					);
				}
			});
		},

		/**
		 * Show validation preview before import.
		 *
		 * @param {Object} data Validation response data.
		 */
		showValidationPreview: function(data) {
			var html = '<div class="macm-validation-summary">';

			// File info.
			if (data.file) {
				html += '<p><strong>File:</strong> ' + this.escapeHtml(data.file.name) +
					' (' + this.escapeHtml(data.file.size) + ')</p>';
			}

			// Source info.
			if (data.metadata && data.metadata.source_site) {
				html += '<p><strong>Source:</strong> ' + this.escapeHtml(data.metadata.source_site) + '</p>';
			}

			// Entities to import.
			html += '<h4>Data to import:</h4><ul>';
			for (var entity in data.entities) {
				var info = data.entities[entity];
				var label = info.label || entity;
				var count = info.count || 0;
				var premium = info.premium ? ' (Premium)' : '';
				html += '<li>' + this.escapeHtml(label) + ': <strong>' + count + '</strong> records' + premium + '</li>';
			}
			html += '</ul>';

			// User mapping info.
			if (data.user_mapping) {
				html += '<p><strong>User Matching:</strong> ' +
					data.user_mapping.matching_users + ' of ' +
					data.user_mapping.emails_found + ' emails match existing users.</p>';
			}

			// Warnings.
			if (data.warnings && data.warnings.length) {
				html += '<div class="macm-warnings"><strong>Warnings:</strong><ul>';
				for (var i = 0; i < data.warnings.length; i++) {
					html += '<li>' + this.escapeHtml(data.warnings[i]) + '</li>';
				}
				html += '</ul></div>';
			}

			html += '</div>';

			this.addLog('File validated successfully. Click "Confirm Import" to proceed.', 'success');
			$('#macm-import-results .macm-results-content').html(html);
			$('#macm-import-results').show();
		},

		/**
		 * Step 2: Execute the actual import.
		 *
		 * @param {jQuery} $form The form element.
		 */
		executeImport: function($form) {
			var self = this;

			// Confirm import.
			if (!confirm(macmDataAdmin.i18n.confirmImport)) {
				return;
			}

			$('#macm-import-btn').prop('disabled', true).text(macmDataAdmin.i18n.importing);
			$('#macm-import-results').hide();
			this.updateProgress(50, 'Importing data...');

			// Prepare data for import.
			var importData = {
				action: 'macm_process_import',
				nonce: macmDataAdmin.nonce,
				import_id: this.importId,
				user_mapping: $('input[name="user_mapping"]:checked').val(),
				conflict_resolution: $('input[name="conflict_resolution"]:checked').val()
			};

			$.ajax({
				url: macmDataAdmin.ajaxUrl,
				type: 'POST',
				data: importData,
				success: function(response) {
					if (response.success) {
						self.updateProgress(100, 'Import completed successfully!');
						self.showResults(response.data);
						self.addLog(response.data.message, 'success');

						// Reset form after successful import.
						self.resetImportForm();
					} else {
						self.showError(response.data.message || macmDataAdmin.i18n.error);
						// Re-enable button on error.
						$('#macm-import-btn').prop('disabled', false).html(
							'<span class="dashicons dashicons-upload"></span> Start Import'
						);
					}
				},
				error: function() {
					self.showError(macmDataAdmin.i18n.error);
					// Re-enable button on error.
					$('#macm-import-btn').prop('disabled', false).html(
						'<span class="dashicons dashicons-upload"></span> Start Import'
					);
				}
			});
		},

		/**
		 * Update progress bar.
		 *
		 * @param {number} percent Progress percentage.
		 * @param {string} status  Status text.
		 */
		updateProgress: function(percent, status) {
			$('.macm-progress-fill').css('width', percent + '%');
			$('.macm-progress-percent').text(percent + '%');
			$('.macm-progress-text').text(status);
		},

		/**
		 * Add log entry.
		 *
		 * @param {string} message Log message.
		 * @param {string} type    Log type (success, error, warning).
		 */
		addLog: function(message, type) {
			var $log = $('.macm-progress-log');
			var className = type ? 'log-' + type : '';
			$log.append('<div class="log-item ' + className + '">' + this.escapeHtml(message) + '</div>');
			$log.scrollTop($log[0].scrollHeight);
		},

		/**
		 * Show import results.
		 *
		 * @param {Object} data Results data.
		 */
		showResults: function(data) {
			var html = '<table>';
			html += '<tr><th>Entity</th><th>Created</th><th>Updated</th><th>Skipped</th><th>Errors</th></tr>';

			if (data.results) {
				for (var entity in data.results) {
					var r = data.results[entity];
					html += '<tr>';
					html += '<td>' + this.escapeHtml(entity) + '</td>';
					html += '<td class="macm-results-success">' + (r.created || 0) + '</td>';
					html += '<td>' + (r.updated || 0) + '</td>';
					html += '<td>' + (r.skipped || 0) + '</td>';
					html += '<td class="macm-results-error">' + (r.errors || 0) + '</td>';
					html += '</tr>';
				}
			}

			html += '</table>';

			$('#macm-import-results .macm-results-content').html(html);
			$('#macm-import-results').show();
		},

		/**
		 * Show error message.
		 *
		 * @param {string} message Error message.
		 */
		showError: function(message) {
			this.updateProgress(0, 'Error');
			this.addLog(message, 'error');
			$('#macm-import-btn').prop('disabled', false).html(
				'<span class="dashicons dashicons-upload"></span> Start Import'
			);
		},

		/**
		 * Format file size.
		 *
		 * @param {number} bytes File size in bytes.
		 * @return {string} Formatted size.
		 */
		formatFileSize: function(bytes) {
			if (bytes === 0) {
				return '0 Bytes';
			}

			var k = 1024;
			var sizes = ['Bytes', 'KB', 'MB', 'GB'];
			var i = Math.floor(Math.log(bytes) / Math.log(k));

			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		},

		/**
		 * Escape HTML entities.
		 *
		 * @param {string} text Text to escape.
		 * @return {string} Escaped text.
		 */
		escapeHtml: function(text) {
			if (typeof text !== 'string') {
				return text;
			}

			var map = {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			};

			return text.replace(/[&<>"']/g, function(m) {
				return map[m];
			});
		},

		/**
		 * Handle reset button click.
		 *
		 * Shows a multi-step confirmation dialog before resetting plugin data.
		 *
		 * @param {Event} e Click event.
		 */
		handleReset: function(e) {
			e.preventDefault();

			var self = this;

			// First confirmation - alert with warning.
			var confirmed = confirm(
				'⚠️ ' + macmDataAdmin.i18n.resetConfirm1 + '\n\n' +
				macmDataAdmin.i18n.resetConfirm2 + '\n\n' +
				'Click OK to continue or Cancel to abort.'
			);

			if (!confirmed) {
				alert(macmDataAdmin.i18n.resetCancelled);
				return;
			}

			// Second confirmation - require typing "RESET".
			var typedConfirm = prompt(
				'⚠️ FINAL WARNING ⚠️\n\n' +
				macmDataAdmin.i18n.resetConfirm1 + '\n\n' +
				macmDataAdmin.i18n.resetConfirm3
			);

			if (typedConfirm === null) {
				alert(macmDataAdmin.i18n.resetCancelled);
				return;
			}

			if (typedConfirm !== 'RESET') {
				alert('Invalid confirmation. You must type "RESET" exactly.\n\n' + macmDataAdmin.i18n.resetCancelled);
				return;
			}

			// User confirmed - proceed with reset.
			self.executeReset();
		},

		/**
		 * Execute the reset operation.
		 *
		 * Sends AJAX request to reset all plugin data.
		 */
		executeReset: function() {
			var self = this;
			var $btn = $('#macm-reset-btn');
			var $progress = $('#macm-reset-progress');
			var $results = $('#macm-reset-results');

			// Show progress, hide results.
			$progress.show();
			$results.hide().removeClass('success error');

			// Disable button and show loading state.
			$btn.prop('disabled', true).html(
				'<span class="dashicons dashicons-update-alt spin"></span> ' +
				macmDataAdmin.i18n.resetting
			);

			// Animate progress bar.
			$('.macm-progress-fill').css('width', '30%');

			// Send AJAX request.
			$.ajax({
				url: macmDataAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'macm_reset_plugin_data',
					nonce: macmDataAdmin.nonce,
					confirm_token: 'RESET'
				},
				success: function(response) {
					$('.macm-progress-fill').css('width', '100%');

					setTimeout(function() {
						$progress.hide();

						if (response.success) {
							self.showResetSuccess(response.data);
						} else {
							self.showResetError(response.data.message || macmDataAdmin.i18n.error);
						}
					}, 500);
				},
				error: function() {
					$progress.hide();
					self.showResetError(macmDataAdmin.i18n.error);
				},
				complete: function() {
					$btn.prop('disabled', false).html(
						'<span class="dashicons dashicons-trash"></span> Reset Plugin Content'
					);
				}
			});
		},

		/**
		 * Show reset success message.
		 *
		 * @param {Object} data Response data.
		 */
		showResetSuccess: function(data) {
			var $results = $('#macm-reset-results');

			$results
				.addClass('success')
				.find('.macm-results-message')
				.html(
					'<strong>' + macmDataAdmin.i18n.resetSuccess + '</strong><br>' +
					'<small>' + data.reset_count + ' tables have been cleared.</small>'
				);

			$results.show();
		},

		/**
		 * Show reset error message.
		 *
		 * @param {string} message Error message.
		 */
		showResetError: function(message) {
			var $results = $('#macm-reset-results');

			$results
				.addClass('error')
				.find('.macm-results-message')
				.html('<strong>Error:</strong> ' + this.escapeHtml(message));

			$results.show();
		},

		/**
		 * Reset import form to initial state.
		 *
		 * Called after successful import to clear file selection,
		 * preview, and reset UI elements.
		 */
		resetImportForm: function() {
			// Clear file input.
			var $fileInput = $('#macm-import-file');
			$fileInput.val('');

			// Reset drag-and-drop text to original.
			$('.macm-file-text').text('Choose file or drag and drop');

			// Hide file preview.
			$('#macm-file-preview').hide();

			// Reset import ID.
			this.importId = null;

			// Reset button text.
			$('#macm-import-btn').prop('disabled', false).html(
				'<span class="dashicons dashicons-upload"></span> Start Import'
			);

			// Clear progress log (keep results visible).
			$('.macm-progress-log').empty();
		}
	};

	// Initialize on document ready.
	$(document).ready(function() {
		MACMDataAdmin.init();
	});

})(jQuery);
