package components

import (
	"context"
	"fmt"
)

// Dialog component for confirmation dialogs using Flowbite modal
templ NotificationDialog(id string, title string, message string, confirmClass string, confirmText string, action string, serviceID uint, serviceName string) {
	<div id={ id } tabindex="-1" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full bg-gray-900/50 dark:bg-gray-900/80 backdrop-blur-sm">
		<div class="relative p-4 w-full max-w-md max-h-full mx-auto">
			<div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
				<div class="p-6 text-center">
					if action == "delete" {
						<i class="fas fa-trash-alt text-red-400 text-3xl mb-4"></i>
					} else {
						<i class="fas fa-exclamation-triangle text-yellow-400 text-3xl mb-4"></i>
					}
					<h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">{ message }</h3>
					<button 
						type="button" 
						class={ confirmClass }
						hx-delete={ fmt.Sprintf("/admin/settings/notifications/%d", serviceID) }
						hx-target="body"
						data-service-name={ serviceName }
						data-service-id={ fmt.Sprint(serviceID) }
						id={ fmt.Sprintf("delete-btn-%d", serviceID) }
						onclick={ triggerServiceDelete(id, serviceID, serviceName) }>
						{ confirmText }
					</button>
					<button type="button" data-modal-hide={ id } class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600">
						Cancel
					</button>
				</div>
			</div>
		</div>
	</div>
}

script hideNotificationDialog(id string) {
	document.getElementById(id).classList.add("hidden");
	document.getElementById(id).classList.remove("flex");
}

script showNotificationDialog(id string) {
	document.getElementById(id).classList.remove("hidden");
	document.getElementById(id).classList.add("flex");
}

script triggerServiceDelete(dialogId string, serviceID uint, serviceName string) {
	// Hide the dialog
	document.getElementById(dialogId).classList.add("hidden");
	document.getElementById(dialogId).classList.remove("flex");
	
	// Add debugging info
	console.log(`Notification service deletion triggered for: ${serviceName} (ID: ${serviceID})`);
	
	// Store data in a way that's accessible to event handlers
	window.lastDeletedService = {
		id: serviceID,
		name: serviceName
	};

	// Add custom marker to track this deletion
	window.currentlyDeletingService = true;
}

templ Notifications(ctx context.Context, data SettingsNotificationsData) {
	@LayoutWithContext("Notification Services", ctx) {
		<!-- Status and Error Messages -->
		<div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-2"></div>
		
		<script>
			// Notification system
			function showToast(message, type) {
				const toastContainer = document.getElementById('toast-container');
				
				// Create toast element
				const toast = document.createElement('div');
				toast.id = 'toast-' + type + '-' + Date.now();
				toast.className = 'flex items-center w-full max-w-xs p-4 mb-4 rounded-lg shadow text-gray-500 bg-white dark:text-gray-400 dark:bg-gray-800 transform translate-y-16 opacity-0 transition-all duration-300 ease-out';
				toast.role = 'alert';
				
				// Set toast content based on type
				let iconClass, bgColorClass, textColorClass;
				
				if (type === 'success') {
					iconClass = 'text-green-500 bg-green-100 dark:bg-green-800 dark:text-green-200';
					bgColorClass = 'text-green-500 dark:text-green-200';
					textColorClass = 'text-green-500 dark:text-green-200';
				} else if (type === 'error') {
					iconClass = 'text-red-500 bg-red-100 dark:bg-red-800 dark:text-red-200';
					bgColorClass = 'text-red-500 dark:text-red-200';
					textColorClass = 'text-red-500 dark:text-red-200';
				} else {
					iconClass = 'text-blue-500 bg-blue-100 dark:bg-blue-800 dark:text-blue-200';
					bgColorClass = 'text-blue-500 dark:text-blue-200';
					textColorClass = 'text-blue-500 dark:text-blue-200';
				}
				
				// Set inner HTML with appropriate icon and message
				toast.innerHTML = `
					<div class="inline-flex items-center justify-center flex-shrink-0 w-8 h-8 rounded-lg ${iconClass}">
						${type === 'success' 
							? '<i class="fas fa-check"></i>' 
							: type === 'error' 
							? '<i class="fas fa-exclamation-circle"></i>'
							: '<i class="fas fa-info-circle"></i>'}
					</div>
					<div class="ml-3 text-sm font-normal">${message}</div>
					<button type="button" class="ml-auto -mx-1.5 -my-1.5 bg-white text-gray-400 hover:text-gray-900 rounded-lg focus:ring-2 focus:ring-gray-300 p-1.5 hover:bg-gray-100 inline-flex h-8 w-8 dark:text-gray-500 dark:hover:text-white dark:bg-gray-800 dark:hover:bg-gray-700" data-dismiss-target="#${toast.id}" aria-label="Close">
						<span class="sr-only">Close</span>
						<i class="fas fa-times"></i>
					</button>
				`;
				
				// Add toast to container
				toastContainer.appendChild(toast);
				
				// Trigger animation after a small delay to ensure the DOM has updated
				setTimeout(() => {
					toast.classList.remove('translate-y-16', 'opacity-0');
					toast.classList.add('translate-y-0', 'opacity-100');
				}, 10);
				
				// Add event listener to close button
				const closeButton = toast.querySelector('button[data-dismiss-target]');
				closeButton.addEventListener('click', function() {
					// Animate out before removing
					toast.classList.add('opacity-0', 'translate-y-4');
					setTimeout(() => {
						toast.remove();
					}, 300);
				});
				
				// Auto-remove toast after 5 seconds
				setTimeout(() => {
					toast.classList.add('opacity-0', 'translate-y-4');
					setTimeout(() => {
						toast.remove();
					}, 300);
				}, 5000);
			}
			
			// Track all HTMX events for debugging
			document.addEventListener('htmx:beforeRequest', function(event) {
				console.log("HTMX before request:", event.detail);
				
				// Check if this is a DELETE request for a notification service
				const path = event.detail.path;
				const method = event.detail.verb;
				
				console.log(`Request path: ${path}, method: ${method}`);
				
				// Pattern match for notification service deletions (e.g., /admin/settings/notifications/123)
				if (path && method === 'DELETE' && path.match(/^\/admin\/settings\/notifications\/\d+$/)) {
					console.log("Detected notification service deletion request via URL pattern");
					
					// This is definitely a delete request - store this information
					window.isServiceDeleteRequest = true;
				}
			});

			document.addEventListener('htmx:afterRequest', function(event) {
				console.log("HTMX after request:", event.detail);
				
				// Check for notification service deletion multiple ways
				const isDeleteRequest = 
					// Check global flag from the triggerServiceDelete function
					window.currentlyDeletingService ||
					// Check flag from beforeRequest handler
					window.isServiceDeleteRequest ||
					// Check URL pattern directly from this event
					(event.detail.pathInfo && 
					 event.detail.pathInfo.requestPath && 
					 event.detail.pathInfo.requestPath.match(/^\/admin\/settings\/notifications\/\d+$/) && 
					 event.detail.verb === 'DELETE');
				
				console.log(`Is delete request: ${isDeleteRequest}`);
				
				// If this is a successful delete request, show notification
				if (isDeleteRequest && event.detail.successful) {
					console.log("Delete request was successful");
					
					let serviceName = "Unknown";
					
					// Try multiple sources for service name
					if (event.detail.elt && event.detail.elt.getAttribute) {
						serviceName = event.detail.elt.getAttribute('data-service-name') || serviceName;
					}
					
					if (serviceName === "Unknown" && window.lastDeletedService) {
						// Fallback to our stored service info
						serviceName = window.lastDeletedService.name;
					}
					
					console.log(`Showing success notification for deleted service: ${serviceName}`);
					showToast(`Notification service "${serviceName}" deleted successfully`, 'success');
					
					// Clear flags
					window.currentlyDeletingService = false;
					window.isServiceDeleteRequest = false;
					window.lastDeletedService = null;
				}
			});
			
			document.addEventListener('htmx:responseError', function(event) {
				console.log("HTMX response error:", event.detail);
				
				// Similar logic as success but for errors
				const isDeleteRequest = 
					window.currentlyDeletingService ||
					window.isServiceDeleteRequest ||
					(event.detail.pathInfo && 
					 event.detail.pathInfo.requestPath && 
					 event.detail.pathInfo.requestPath.match(/^\/admin\/settings\/notifications\/\d+$/) && 
					 event.detail.verb === 'DELETE');
				
				let errorMsg = 'An error occurred';
				if (event.detail.xhr && event.detail.xhr.responseText) {
					errorMsg = event.detail.xhr.responseText;
				}
				
				if (isDeleteRequest) {
					console.log("Delete request failed");
					
					let serviceName = "Unknown";
					
					// Try multiple sources for service name
					if (event.detail.elt && event.detail.elt.getAttribute) {
						serviceName = event.detail.elt.getAttribute('data-service-name') || serviceName;
					}
					
					if (serviceName === "Unknown" && window.lastDeletedService) {
						// Fallback to our stored service info
						serviceName = window.lastDeletedService.name;
					}
					
					let errorMsg = `Failed to delete notification service "${serviceName}"`;
					
					if (event.detail.xhr && event.detail.xhr.responseText) {
						errorMsg = `Error: ${event.detail.xhr.responseText}`;
					}
					
					console.log(`Showing error notification: ${errorMsg}`);
					showToast(errorMsg, 'error');
					
					// Clear flags
					window.currentlyDeletingService = false;
					window.isServiceDeleteRequest = false;
					window.lastDeletedService = null;
				} else {
					showToast(errorMsg, 'error');
				}
			});
			
			// Handle modal hide buttons
			document.addEventListener('DOMContentLoaded', function() {
				const hideButtons = document.querySelectorAll('[data-modal-hide]');
				hideButtons.forEach(button => {
					button.addEventListener('click', function() {
						const modalId = this.getAttribute('data-modal-hide');
						const modal = document.getElementById(modalId);
						modal.classList.add('hidden');
						modal.classList.remove('flex');
					});
				});
				
				// Show any success or error messages as toasts
				if (document.querySelector('.success-message')) {
					const successMsg = document.querySelector('.success-message').textContent.trim();
					if (successMsg) {
						showToast(successMsg, 'success');
					}
				}
				
				if (document.querySelector('.error-message')) {
					const errorMsg = document.querySelector('.error-message').textContent.trim();
					if (errorMsg) {
						showToast(errorMsg, 'error');
					}
				}
			});
		</script>
		
		<div id="notifications-container" style="min-height: 100vh; background-color: rgb(249, 250, 251);" class="notifications-page bg-gray-50 dark:bg-gray-900">
			<div class="pb-8 w-full">
				<!-- Success Message (hidden, used for HTMX responses) -->
				if data.SuccessMessage != "" {
					<div class="hidden success-message">{ data.SuccessMessage }</div>
				}
				<!-- Error Message (hidden, used for HTMX responses) -->
				if data.ErrorMessage != "" {
					<div class="hidden error-message">{ data.ErrorMessage }</div>
				}
				
				<div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
					<h1 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center">
						<i class="fas fa-bell w-6 h-6 mr-2 text-blue-500 dark:text-blue-400"></i>
						Notification Services
					</h1>
					<a href="/admin/settings/notifications/new" class="flex items-center justify-center text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
						<i class="fas fa-plus w-4 h-4 mr-2"></i>
						Add Notification Service
					</a>
				</div>
				
				<!-- List of Notification Services -->
				if len(data.NotificationServices) == 0 {
					<div class="text-center py-8 bg-white dark:bg-gray-800 shadow-md rounded-lg">
						<div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900 mb-4">
							<i class="fas fa-bell text-2xl text-blue-600 dark:text-blue-400"></i>
						</div>
						<h3 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white">No notification services configured</h3>
						<p class="text-gray-500 dark:text-gray-400 mb-4">Add a notification service to receive alerts for job events.</p>
						<a href="/admin/settings/notifications/new" class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-blue-700 rounded-lg hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
							<i class="fas fa-plus w-4 h-4 mr-2"></i>
							Add First Notification Service
						</a>
					</div>
				} else {
					<div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 overflow-hidden">
						<ul class="divide-y divide-gray-200 dark:divide-gray-700">
							for _, service := range data.NotificationServices {
								<li>
									<div class="block hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
										<div class="px-4 py-4 sm:px-6">
											<div class="flex items-center justify-between">
												<div class="flex items-center">
													if service.Type == "email" {
														<div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 dark:bg-blue-900 dark:text-blue-400 mr-3">
															<i class="fas fa-envelope"></i>
														</div>
													} else if service.Type == "webhook" {
														<div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600 dark:bg-green-900 dark:text-green-400 mr-3">
															<i class="fas fa-code"></i>
														</div>
													} else {
														<div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 dark:bg-gray-700 dark:text-gray-400 mr-3">
															<i class="fas fa-bell"></i>
														</div>
													}
													<div>
														<p class="text-sm font-medium text-blue-600 dark:text-blue-400 truncate">
															{ service.Name }
														</p>
														<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
															{ service.Description }
														</p>
													</div>
												</div>
												<div class="ml-2 flex-shrink-0 flex space-x-2">
													<a 
														href={ templ.SafeURL(fmt.Sprintf("/admin/settings/notifications/%d/edit", service.ID)) }
														class="text-gray-500 bg-white focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2 mr-1 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700"
													>
														<i class="fas fa-edit"></i>
													</a>
													<!-- Add notification delete dialog -->
													@NotificationDialog(
														fmt.Sprintf("delete-notification-dialog-%d", service.ID),
														"Delete Notification Service",
														fmt.Sprintf("Are you sure you want to delete the notification service '%s'? This cannot be undone.", service.Name),
														"text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-red-600 dark:hover:bg-red-700 focus:outline-none dark:focus:ring-red-800",
														"Delete",
														"delete",
														service.ID,
														service.Name,
													)
													<button
														type="button"
														onclick={ showNotificationDialog(fmt.Sprintf("delete-notification-dialog-%d", service.ID)) }
														class="text-red-500 bg-white focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2 dark:bg-gray-800 dark:text-red-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700"
													>
														<i class="fas fa-trash-alt"></i>
													</button>
												</div>
											</div>
											<div class="mt-3 sm:flex sm:justify-between">
												<div class="sm:flex flex-col md:flex-row gap-2 md:gap-6">
													<div class="flex items-center">
														<span
															class={ "px-2 py-1 text-xs font-medium rounded-full", 
															templ.KV("bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300", service.IsEnabled),
															templ.KV("bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300", !service.IsEnabled) }
														>
															if service.IsEnabled {
																Active
															} else {
																Disabled
															}
														</span>
														<span class="ml-2 px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300 rounded-full">
															{ service.Type }
														</span>
														if len(service.EventTriggers) > 0 && service.Type == "webhook" {
															<span class="ml-2 px-2 py-1 text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300 rounded-full">
																{ fmt.Sprintf("%d triggers", len(service.EventTriggers)) }
															</span>
														}
														if service.SuccessCount > 0 || service.FailureCount > 0 {
															<span class="ml-2 px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300 rounded-full">
																{ fmt.Sprintf("%d/%d", service.SuccessCount, service.SuccessCount + service.FailureCount) }
															</span>
														}
													</div>
												</div>
												if service.Type == "webhook" {
													<div class="mt-2 md:mt-0 flex items-center space-x-4">
														<div class="text-xs">
															<span class="text-gray-500 dark:text-gray-400">Events:</span>
															<span class="ml-1 text-gray-900 dark:text-gray-300">
																if len(service.EventTriggers) == 0 {
																	None
																} else {
																	for i, trigger := range service.EventTriggers {
																		if i > 0 {
																			<span>, </span>
																		}
																		{ trigger }
																	}
																}
															</span>
														</div>
														<div class="text-xs">
															<span class="text-gray-500 dark:text-gray-400">Retry:</span>
															<span class="ml-1 text-gray-900 dark:text-gray-300">
																if service.RetryPolicy == "" {
																	Default
																} else {
																	{ service.RetryPolicy }
																}
															</span>
														</div>
													</div>
												} else {
													<div class="mt-2 md:mt-0 flex items-center text-sm text-gray-500 dark:text-gray-400">
														<i class="far fa-clock w-4 h-4 mr-1.5 text-gray-400 dark:text-gray-500"></i>
														<p>
															Last sent: 
															if service.SuccessCount > 0 {
																"Recently"
															} else {
																"Never"
															}
														</p>
													</div>
												}
											</div>
										</div>
									</div>
								</li>
							}
						</ul>
					</div>
				}
				
				<!-- Help Notice -->
				<div class="mt-8 p-4 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-800 dark:border-gray-700">
					<div class="flex">
						<div class="flex-shrink-0">
							<i class="fas fa-info-circle text-blue-400 dark:text-blue-400"></i>
						</div>
						<div class="ml-3">
							<p class="text-sm text-blue-700 dark:text-blue-400">
								Notification services allow the system to send alerts for job events such as completion, errors, or when jobs start.
							</p>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<script>
			// Set dark background color if in dark mode
			if (document.documentElement.classList.contains('dark')) {
				document.getElementById('notifications-container').style.backgroundColor = '#111827';
			}
			
			// Add event listener for theme changes
			document.addEventListener('DOMContentLoaded', function() {
				const themeToggle = document.getElementById('theme-toggle');
				if (themeToggle) {
					themeToggle.addEventListener('click', function() {
						setTimeout(function() {
							const isDark = document.documentElement.classList.contains('dark');
							document.getElementById('notifications-container').style.backgroundColor = isDark ? '#111827' : 'rgb(249, 250, 251)';
						}, 50);
					});
				}
			});
		</script>
	}
}