/**
 * Job Monitor
 *
 * Monitors and displays background job status with auto-refresh,
 * job cancellation, and cleanup capabilities.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.jobMonitor
 */

(function($) {
	'use strict';

	const AgenticWPAdmin = window.AgenticWPAdmin = window.AgenticWPAdmin || {};
	const utils = AgenticWPAdmin.utils || {};

	/**
	 * Gets admin data from global object.
	 *
	 * @return {Object} Admin data object.
	 */
	function getAdminData() {
		return window.agenticwpAdmin || {};
	}

	/**
	 * Configuration for job status display.
	 *
	 * @type {Object}
	 */
	const STATUS_CONFIG = {
		queued: { cssClass: 'queued', label: 'Queued' },
		starting: { cssClass: 'starting', label: 'Starting' },
		polling: { cssClass: 'polling', label: 'In Progress' },
		complete: { cssClass: 'complete', label: 'Complete' },
		failed: { cssClass: 'failed', label: 'Failed' },
		cancelled: { cssClass: 'cancelled', label: 'Cancelled' }
	};

	let refreshInterval = null;

	/**
	 * Initializes job monitor.
	 */
	function init() {
		if (!$('#agenticwp-jobs-monitor').length) {
			return;
		}

		bindEvents();
		fetchJobStatus();

		if ($('#agenticwp-auto-refresh').prop('checked')) {
			startAutoRefresh();
		}
	}

	function bindEvents() {
		$(document).on('change', '#agenticwp-show-completed', updateJobDisplay);

		$(document).on('change', '#agenticwp-auto-refresh', function() {
			const isEnabled = $(this).prop('checked');
			if (isEnabled) {
				startAutoRefresh();
			} else {
				stopAutoRefresh();
			}
		});

		$(document).on('click', '#agenticwp-refresh-jobs', function(event) {
			event.preventDefault();
			fetchJobStatus();
		});

		$(document).on('click', '#agenticwp-cleanup-jobs', function(event) {
			event.preventDefault();
			cleanupCompletedJobs();
		});

		$(document).on('click', '.agenticwp-cancel-job', function(event) {
			event.preventDefault();
			const jobId = $(this).data('job-id');
			if (jobId) {
				cancelJob(jobId, $(this));
			}
		});
	}

	/**
	 * Starts auto-refresh interval.
	 */
	function startAutoRefresh() {
		stopAutoRefresh();
		refreshInterval = window.setInterval(fetchJobStatus, 5000);
	}

	function stopAutoRefresh() {
		if (refreshInterval) {
			window.clearInterval(refreshInterval);
			refreshInterval = null;
		}
	}

	function fetchJobStatus() {
		const adminData = getAdminData();

		utils.postAction({
			action: 'agenticwp_get_job_status',
			nonce: adminData.jobStatusNonce,
			onSuccess: function(response) {
				if (response && response.success) {
					updateJobDisplay(response.data.jobs);
				} else {
					const message = response && response.data && response.data.message ? response.data.message : 'Unknown error';
					const errorCode = response && response.data && response.data.code ? response.data.code : 'unknown';
					utils.logError('job_monitor', {
						error: 'fetch_failed',
						action: 'agenticwp_get_job_status',
						message: message,
						code: errorCode
					});
				}
			},
			onError: function(error) {
				utils.logError('job_monitor', {
					error: 'ajax_error',
					action: 'agenticwp_get_job_status',
					details: error
				});
			}
		});
	}

	function updateJobDisplay(jobs) {
		if (!jobs) {
			jobs = window.agenticwpJobsData || {};
		} else {
			window.agenticwpJobsData = jobs;
		}

		const $container = $('#agenticwp-jobs-list');
		const showCompleted = $('#agenticwp-show-completed').prop('checked');

		if (!jobs || !Object.keys(jobs).length) {
			$container.html('<div class="agenticwp-no-jobs">No background jobs found.</div>');
			return;
		}

		const jobsArray = Object.keys(jobs).map(function(jobId) {
			const job = jobs[jobId] || {};
			job.id = jobId;
			return job;
		});

		jobsArray.sort(function(a, b) {
			const timeA = a.created_at ? a.created_at : 0;
			const timeB = b.created_at ? b.created_at : 0;
			return timeB - timeA;
		});

		let html = '';

		jobsArray.forEach(function(job) {
			if (!showCompleted && isFinishedJob(job.status)) {
				return;
			}

			html += renderJobCard(job);
		});

		if (!html) {
			$container.html('<div class="agenticwp-no-jobs">No jobs to display with current filters.</div>');
			return;
		}

		$container.html(html);
	}

	function isFinishedJob(status) {
		return status === 'complete' || status === 'failed' || status === 'cancelled';
	}

	function renderJobCard(job) {
		const config = STATUS_CONFIG[job.status] || { cssClass: 'unknown', label: 'Unknown' };
		const timeAgo = job.created_at ? formatTimeAgo(job.created_at) : 'Unknown';

		let displayText = job.type || 'Unknown';
		if (job.prompt && job.prompt.trim()) {
			displayText = job.prompt.length > 80 ?
				job.prompt.substring(0, 80) + '...' :
				job.prompt;
		}

		const errorMarkup = job.error ? '<div class="agenticwp-job-error">Error: ' + job.error + '</div>' : '';

		const cancellableStatuses = ['queued', 'starting', 'polling'];
		const canCancel = cancellableStatuses.includes(job.status);
		const cancelButton = canCancel ?
			'<button class="agenticwp-cancel-job button button-secondary" data-job-id="' + job.id + '">Cancel</button>' : '';

		return (
			'<div class="agenticwp-job-card agenticwp-job-' + config.cssClass + '">' +
				'<div class="agenticwp-job-header">' +
					'<div class="agenticwp-job-info">' +
						'<div class="agenticwp-job-type">' + displayText + '</div>' +
						'<div class="agenticwp-job-time">' + timeAgo + '</div>' +
					'</div>' +
					'<div class="agenticwp-job-actions">' +
						'<div class="agenticwp-job-status agenticwp-status-' + config.cssClass + '">' +
							config.label +
						'</div>' +
						cancelButton +
					'</div>' +
				'</div>' +
				errorMarkup +
			'</div>'
		);
	}

	function formatTimeAgo(timestamp) {
		try {
			const now = new Date();
			const time = new Date(timestamp * 1000);
			const diff = now - time;
			const minutes = Math.floor(diff / 60000);
			const hours = Math.floor(minutes / 60);

			if (minutes < 1) {
				return 'Just now';
			}

			if (minutes < 60) {
				return minutes + 'm ago';
			}

			if (hours < 24) {
				return hours + 'h ago';
			}

			return time.toLocaleDateString();
		} catch (error) {
			return 'Unknown';
		}
	}

	function cleanupCompletedJobs() {
		const $button = $('#agenticwp-cleanup-jobs');
		if (!$button.length) {
			return;
		}

		const adminData = getAdminData();

		utils.toggleButtonLoading($button, true, 'Cleaning up...');

		utils.postAction({
			action: 'agenticwp_cleanup_jobs',
			nonce: adminData.jobCleanupNonce,
			onSuccess: function(response) {
				if (response && response.success) {
					updateJobDisplay(response.data.jobs);
					utils.showNotice(response.data.message, 'success');
					return;
				}

				const message = response && response.data && response.data.message ? response.data.message : 'Cleanup failed';
				const errorCode = response && response.data && response.data.code ? response.data.code : 'unknown';
				utils.logError('job_monitor', {
					error: 'cleanup_failed',
					action: 'agenticwp_cleanup_jobs',
					message: message,
					code: errorCode
				});
				utils.showNotice(message, 'error');
			},
			onError: function(error) {
				utils.logError('job_monitor', {
					error: 'ajax_error',
					action: 'agenticwp_cleanup_jobs',
					details: error
				});
				utils.showNotice('Network error during cleanup: ' + error, 'error');
			},
			onComplete: function() {
				window.setTimeout(function() {
					utils.toggleButtonLoading($button, false);
				}, 2500);
			}
		});
	}

	function cancelJob(jobId, $button) {
		if (!$button || !$button.length) {
			return;
		}

		const adminData = getAdminData();

		utils.toggleButtonLoading($button, true, 'Cancelling...');

		utils.postAction({
			action: 'agenticwp_cancel_job',
			nonce: adminData.jobCancelNonce,
			data: { job_id: jobId },
			onSuccess: function(response) {
				if (response && response.success) {
					utils.showNotice(response.data.message, 'success');
					fetchJobStatus();
					return;
				}

				const message = response && response.data && response.data.message ? response.data.message : 'Cancel failed';
				const errorCode = response && response.data && response.data.code ? response.data.code : 'unknown';
				utils.logError('job_monitor', {
					error: 'cancel_failed',
					action: 'agenticwp_cancel_job',
					job_id: jobId,
					message: message,
					code: errorCode
				});
				utils.showNotice(message, 'error');
			},
			onError: function(error) {
				utils.logError('job_monitor', {
					error: 'ajax_error',
					action: 'agenticwp_cancel_job',
					job_id: jobId,
					details: error
				});
				utils.showNotice('Network error during cancellation: ' + error, 'error');
			},
			onComplete: function() {
				window.setTimeout(function() {
					utils.toggleButtonLoading($button, false);
				}, 1000);
			}
		});
	}

	AgenticWPAdmin.jobMonitor = {
		init: init
	};
})(jQuery);
