package components

import (
	"context"
	"fmt"
	"github.com/starfleetcptn/gomft/internal/db"
)

// Dialog component for confirmation dialogs using Flowbite modal
templ ConfigDialog(id string, title string, message string, confirmClass string, confirmText string, action string, configID uint, configName 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-circle 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("/configs/%d", configID) }
						hx-target="closest li"
						hx-swap="delete"
						data-config-name={ configName }
						data-config-id={ fmt.Sprint(configID) }
						id={ fmt.Sprintf("delete-config-btn-%d", configID) }
						onclick={ triggerConfigDelete(id, configID, configName) }>
						{ 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 hideConfigDialog(id string) {
	document.getElementById(id).classList.add("hidden");
	document.getElementById(id).classList.remove("flex");
}

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

script triggerConfigDelete(dialogId string, configID uint, configName string) {
	// Hide the dialog
	document.getElementById(dialogId).classList.add("hidden");
	document.getElementById(dialogId).classList.remove("flex");
		
	// Store data in a way that's accessible to event handlers
	window.lastDeletedConfig = {
		id: configID,
		name: configName
	};

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

type ConfigsData struct {
	Configs []db.TransferConfig
	Error string
	ErrorDetails string
	Status string
}

templ Configs(ctx context.Context, data ConfigsData) {
	@LayoutWithContext("Transfer Configurations", ctx) {
		<!-- Status and Error Messages -->
		<div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-2"></div>
		
		<script>
			// Debug notification system
			console.log("Configs template loaded, setting up notification system");
			
			// Function to create and show a toast
			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);
			}

			// Show status messages based on URL parameters
			document.addEventListener('DOMContentLoaded', function() {
				// Check for error message
				const urlParams = new URLSearchParams(window.location.search);
				const errorMsg = urlParams.get('error');
				const errorDetails = urlParams.get('details');
				const status = urlParams.get('status');
				
				if (errorMsg) {
					let message = errorMsg;
					if (errorDetails) {
						message += ": " + errorDetails;
					}
					showToast(message, 'error');
				}
				
				if (status === 'gdrive_auth_success') {
					showToast("Google Drive authentication completed successfully", 'success');
				}
				
				// Handle modal hide buttons
				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');
					});
				});
			});

			// Track all HTMX events for debugging
			document.addEventListener('htmx:beforeRequest', function(event) {
				
				// Check if this is a DELETE request by examining the URL and method
				const path = event.detail.path;
				const method = event.detail.verb;
								
				// Pattern match for config deletions (e.g., /configs/123)
				if (path && method === 'DELETE' && path.match(/^\/configs\/\d+$/)) {
					
					// This is definitely a delete request - store this information
					window.isConfigDeleteRequest = true;
				}
				
				// Check if this is a duplication request
				if (path && method === 'POST' && path.match(/^\/configs\/\d+\/duplicate$/)) {
					window.isConfigDuplicateRequest = true;
					
					// Store the config ID for reference
					const configId = path.match(/^\/configs\/(\d+)\/duplicate$/)[1];
					const configButton = document.querySelector(`button[hx-post="/configs/${configId}/duplicate"]`);
					if (configButton) {
						window.duplicatingConfigName = configButton.closest('li').querySelector('.text-blue-600').textContent.trim();
					}
				}
			});

			// Track HTMX after-request events for config deletion
			document.addEventListener('htmx:afterRequest', function(event) {
				
				// Check for config deletion multiple ways
				const isDeleteRequest = 
					// Check global flag from the triggerConfigDelete function
					window.currentlyDeletingConfig ||
					// Check flag from beforeRequest handler
					window.isConfigDeleteRequest ||
					// Check URL pattern directly from this event
					(event.detail.pathInfo && event.detail.pathInfo.requestPath && 
					 event.detail.pathInfo.requestPath.match(/^\/configs\/\d+$/) && 
					 event.detail.verb === 'DELETE');
				
				
				// If this is a successful delete request, show notification
				if (isDeleteRequest && event.detail.successful) {
					
					let configName = "Unknown";
					
					// Try multiple sources for config name
					if (event.detail.elt && event.detail.elt.getAttribute) {
						configName = event.detail.elt.getAttribute('data-config-name') || configName;
					}
					
					if (configName === "Unknown" && window.lastDeletedConfig) {
						// Fallback to our stored config info
						configName = window.lastDeletedConfig.name;
					}
					
					showToast(`Configuration "${configName}" deleted successfully`, 'success');
					
					// Clear flags
					window.currentlyDeletingConfig = false;
					window.isConfigDeleteRequest = false;
					window.lastDeletedConfig = null;
				}
				
				// Check if this is a duplication request
				const isDuplicateRequest = window.isConfigDuplicateRequest && 
					event.detail.pathInfo && 
					event.detail.pathInfo.requestPath && 
					event.detail.pathInfo.requestPath.match(/^\/configs\/\d+\/duplicate$/);
				
				// If this is a successful duplication request, show notification
				if (isDuplicateRequest && event.detail.successful) {
					const configName = window.duplicatingConfigName || "configuration";
					showToast(`Configuration "${configName}" duplicated successfully`, 'success');
					
					// Clear flags
					window.isConfigDuplicateRequest = false;
					window.duplicatingConfigName = null;
				}
			});
			
			// Track HTMX error events for config deletion
			document.addEventListener('htmx:responseError', function(event) {
				
				// Similar logic as success but for errors
				const isDeleteRequest = 
					window.currentlyDeletingConfig ||
					window.isConfigDeleteRequest ||
					(event.detail.pathInfo && event.detail.pathInfo.requestPath && 
					 event.detail.pathInfo.requestPath.match(/^\/configs\/\d+$/) && 
					 event.detail.verb === 'DELETE');
				
				if (isDeleteRequest) {
					
					let configName = "Unknown";
					
					// Try multiple sources for config name
					if (event.detail.elt && event.detail.elt.getAttribute) {
						configName = event.detail.elt.getAttribute('data-config-name') || configName;
					}
					
					if (configName === "Unknown" && window.lastDeletedConfig) {
						// Fallback to our stored config info
						configName = window.lastDeletedConfig.name;
					}
					
					let errorMsg = `Failed to delete configuration "${configName}"`;
					
					if (event.detail.xhr && event.detail.xhr.responseText) {
						errorMsg = event.detail.xhr.responseText
						// error message is a json object
						const error = JSON.parse(errorMsg);
						errorMsg = `Error: ${error.error}`;
					}
					
					showToast(errorMsg, 'error');
					
					// Clear flags
					window.currentlyDeletingConfig = false;
					window.isConfigDeleteRequest = false;
					window.lastDeletedConfig = null;
				}
				
				// Check if this is a duplication request
				const isDuplicateRequest = window.isConfigDuplicateRequest && 
					event.detail.pathInfo && 
					event.detail.pathInfo.requestPath && 
					event.detail.pathInfo.requestPath.match(/^\/configs\/\d+\/duplicate$/);
				
				if (isDuplicateRequest) {
					const configName = window.duplicatingConfigName || "configuration";
					
					let errorMsg = `Failed to duplicate configuration "${configName}"`;
					
					if (event.detail.xhr && event.detail.xhr.responseText) {
						try {
							const error = JSON.parse(event.detail.xhr.responseText);
							errorMsg = `Error: ${error.error}`;
						} catch (e) {
							// If not JSON, use the response text directly
							if (event.detail.xhr.responseText.trim()) {
								errorMsg = event.detail.xhr.responseText;
							}
						}
					}
					
					showToast(errorMsg, 'error');
					
					// Clear flags
					window.isConfigDuplicateRequest = false;
					window.duplicatingConfigName = null;
				}
			});
		</script>
		
		<div id="configs-container" style="min-height: 100vh; background-color: rgb(249, 250, 251);" class="configs-page bg-gray-50 dark:bg-gray-900">
			<div class="pb-8 w-full">
				<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-exchange-alt w-6 h-6 mr-2 text-blue-500 dark:text-blue-400"></i>
						Transfer Configurations
					</h1>
					<a href="/configs/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>
						New Configuration
					</a>
				</div>
				
				<div class="mt-6">
					if len(data.Configs) == 0 {
						<div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 p-8 flex flex-col items-center justify-center text-center">
							<div class="inline-flex h-16 w-16 flex-shrink-0 items-center justify-center rounded-full bg-gray-100 mb-4 dark:bg-gray-700">
								<i class="fas fa-exchange-alt text-gray-400 dark:text-gray-500 text-3xl"></i>
							</div>
							<h3 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white">No configurations</h3>
							<p class="text-gray-500 dark:text-gray-400 mb-4">Get started by creating a new transfer configuration.</p>
							<a href="/configs/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>
								Create First Configuration
							</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 _, config := range data.Configs {
									<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">
														<p class="text-sm font-medium text-blue-600 dark:text-blue-400 truncate">
															{ config.Name }
														</p>

														<!-- Google Drive Authentication Badge -->
														if (config.DestinationType == "gdrive" || config.SourceType == "gdrive" || config.SourceType == "gphotos" || config.DestinationType == "gphotos") && !config.GetGoogleAuthenticated() {
															<span class="ml-2 bg-yellow-100 text-yellow-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full dark:bg-yellow-900 dark:text-yellow-300">
																<i class="fas fa-exclamation-triangle w-3 h-3 mr-1 inline"></i>
																Authentication Required
															</span>
														}
														
														<!-- Google Drive Authentication Status Indicator -->
														if (config.DestinationType == "gdrive" || config.SourceType == "gdrive" || config.SourceType == "gphotos" || config.DestinationType == "gphotos") && config.GetGoogleAuthenticated() {
															<span class="ml-2 bg-green-100 text-green-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full dark:bg-green-900 dark:text-green-300">
																<i class="fas fa-check-circle w-3 h-3 mr-1 inline"></i>
																Authenticated
															</span>
														}
													</div>
													<div class="ml-2 flex-shrink-0 flex space-x-2">
														<!-- Google Drive Authentication Button -->
														if (config.DestinationType == "gdrive" || config.SourceType == "gdrive" || config.SourceType == "gphotos" || config.DestinationType == "gphotos") && !config.GetGoogleAuthenticated() {
															<a href={ templ.SafeURL(fmt.Sprintf("/configs/%d/gdrive-auth", config.ID)) } class="text-yellow-700 bg-yellow-100 hover:bg-yellow-200 focus:ring-4 focus:outline-none focus:ring-yellow-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center dark:bg-yellow-900 dark:text-yellow-300 dark:hover:bg-yellow-800 dark:focus:ring-yellow-800">
																<i class="fas fa-key w-3.5 h-3.5 mr-1.5"></i>
																Authenticate
															</a>
														}
														
														<a href={ templ.SafeURL(fmt.Sprintf("/configs/%d", config.ID)) } class="text-gray-700 bg-gray-100 hover:bg-gray-200 focus:ring-4 focus:outline-none focus:ring-gray-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 dark:focus:ring-gray-700">
															<i class="fas fa-edit w-3.5 h-3.5 mr-1.5"></i>
															Edit
														</a>
														<!-- Duplicate config button -->
														<button 
															type="button"
															hx-post={ fmt.Sprintf("/configs/%d/duplicate", config.ID) }
															hx-target="body"
															class="text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:ring-4 focus:outline-none focus:ring-indigo-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center dark:bg-indigo-700 dark:text-indigo-300 dark:hover:bg-indigo-600 dark:focus:ring-indigo-800">
															<i class="fas fa-clone w-3.5 h-3.5 mr-1.5"></i>
															Duplicate
														</button>
														<!-- Add delete dialog for each configuration -->
														@ConfigDialog(
															fmt.Sprintf("delete-config-dialog-%d", config.ID),
															"Delete Configuration",
															fmt.Sprintf("Are you sure you want to delete the configuration '%s'? This cannot be undone.", config.Name),
															"text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center",
															"Delete",
															"delete",
															config.ID,
															config.Name,
														)
														<button 
															type="button"
															onclick={ showConfigDialog(fmt.Sprintf("delete-config-dialog-%d", config.ID)) }
															class="text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-800">
															<i class="fas fa-trash-alt w-3.5 h-3.5 mr-1.5"></i>
															Delete
														</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">
														<p class="flex items-center text-sm text-gray-500 dark:text-gray-400">
															<i class="fas fa-upload w-4 h-4 mr-1.5 text-gray-400 dark:text-gray-500"></i>
															Source: { config.SourceType }: { config.SourcePath }
														</p>
														<p class="mt-2 md:mt-0 flex items-center text-sm text-gray-500 dark:text-gray-400">
															<i class="fas fa-download w-4 h-4 mr-1.5 text-gray-400 dark:text-gray-500"></i>
															Destination: { config.DestinationType }: { config.DestinationPath }
														</p>
													</div>
													<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>
															Updated: { config.UpdatedAt.Format("2006-01-02 15:04:05") }
														</p>
													</div>
												</div>
											</div>
										</div>
									</li>
								}
							</ul>
						</div>
					}
				</div>
				
				<!-- Help Section -->
				<div class="bg-gray-50 dark:bg-gray-800 rounded-lg shadow-sm mt-8 p-4 border border-gray-200 dark:border-gray-700">
					<div class="flex items-start mb-2">
						<div class="flex items-center h-5">
							<i class="fas fa-info-circle w-4 h-4 text-blue-500 dark:text-blue-400 mr-2"></i>
						</div>
						<div class="ml-2 text-sm">
							<p class="text-gray-700 dark:text-gray-300">Configurations define how files are transferred between systems</p>
						</div>
					</div>

					<div class="flex items-start mt-4">
						<div class="flex items-center h-5">
							<i class="fab fa-google-drive w-4 h-4 text-blue-500 dark:text-blue-400 mr-2"></i>
						</div>
						<div class="ml-2 text-sm">
							<p class="text-gray-700 dark:text-gray-300">Google Drive and Google Photos configurations require authentication. Click the "Authenticate" button to complete setup.</p>
						</div>
					</div>

					<div class="flex items-start mt-4">
						<div class="flex items-center h-5">
							<i class="fas fa-clone w-4 h-4 text-indigo-500 dark:text-indigo-400 mr-2"></i>
						</div>
						<div class="ml-2 text-sm">
							<p class="text-gray-700 dark:text-gray-300">When duplicating configurations, you may need to re-enter sensitive credentials for security reasons. Make sure to edit duplicated configurations to add any required credentials.</p>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<script>
			// Set dark background color if in dark mode
			if (document.documentElement.classList.contains('dark')) {
				document.getElementById('configs-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('configs-container').style.backgroundColor = isDark ? '#111827' : 'rgb(249, 250, 251)';
						}, 50);
					});
				}
			});
		</script>
	}
}