package components

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

type UserManagementData struct {
	Users          []db.User
	Roles          []db.Role
	ActiveTab      string // "list", "create", or "edit"
	EditUser       *db.User
	UserRoles      []db.Role
	ErrorMessage   string
	SuccessMessage string
}

templ UserManagement(ctx context.Context, data UserManagementData) {
	@LayoutWithContext("User Management", ctx) {
		@UserManagementContent(data)
	}
}

// UserManagementContent is a partial component for HTMX to replace only the content
templ UserManagementContent(data UserManagementData) {
	// <div id="userManagementContainer" class="px-4 py-8 mx-auto max-w-screen-xl lg:px-6">
	<div id="userManagementContainer" style="min-height: 100vh;" class="bg-gray-50 dark:bg-gray-900">
		<div class="pb-8 w-full">
			<!-- Toast container for status messages -->
			<div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-2"></div>
			
			<script>
				// 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);
				}
				
				// 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');
						});
					});
				});
				
				// Track user operations in HTMX events
				document.addEventListener('htmx:beforeRequest', function(event) {
					console.log("HTMX before request:", event.detail);
					
					// Check if this is a DELETE request for a user
					const path = event.detail.path;
					const method = event.detail.verb;
					
					console.log(`Request path: ${path}, method: ${method}`);
					
					// Pattern match for user deletions (e.g., /admin/users/123)
					if (path && method === 'DELETE' && path.match(/^\/admin\/users\/\d+$/)) {
						console.log("Detected user deletion request via URL pattern");
						
						// This is definitely a delete request - store this information
						window.isUserDeleteRequest = true;
					}
				});
				
				// Track HTMX events for user operations
				document.addEventListener('htmx:afterRequest', function(event) {
					// Check if the request was successful
					if (event.detail.successful) {
						// Check for POST, PUT, DELETE operations
						const path = event.detail.pathInfo?.requestPath || '';
						const method = event.detail.verb || '';
						
						// User deletion handling
						const isDeleteRequest = 
							window.currentlyDeletingUser ||
							window.isUserDeleteRequest ||
							(method === 'DELETE' && path.match(/^\/admin\/users\/\d+$/));
						
						if (isDeleteRequest) {
							let userEmail = "user";
							
							// Try multiple sources for user email
							if (event.detail.elt && event.detail.elt.getAttribute) {
								userEmail = event.detail.elt.getAttribute('data-user-email') || userEmail;
							}
							
							if (userEmail === "user" && window.lastDeletedUser) {
								// Fallback to our stored user info
								userEmail = window.lastDeletedUser.email;
							}
							
							showToast(`User "${userEmail}" deleted successfully`, 'success');
							
							// Clear flags
							window.currentlyDeletingUser = false;
							window.isUserDeleteRequest = false;
							window.lastDeletedUser = null;
							return;
						}
						
						// User creation
						if (method === 'POST' && path === '/admin/users') {
							// Find the email from the form data if possible
							const formData = event.detail.requestConfig?.parameters;
							let email = "New user";
							if (formData && formData.email) {
								email = formData.email;
							}
							showToast(`User "${email}" created successfully`, 'success');
							return;
						}
						
						// User update
						if (method === 'PUT' && path.match(/^\/admin\/users\/\d+$/)) {
							// Find the email from the form data if possible
							const formData = event.detail.requestConfig?.parameters;
							let email = "User";
							if (formData && formData.email) {
								email = formData.email;
							}
							showToast(`User "${email}" updated successfully`, 'success');
							return;
						}
					}
				});
				
				// Track HTMX error events
				document.addEventListener('htmx:responseError', function(event) {
					console.log("HTMX response error:", event.detail);
					
					// Check for delete request errors
					const isDeleteRequest = 
						window.currentlyDeletingUser ||
						window.isUserDeleteRequest ||
						(event.detail.requestConfig && 
						 event.detail.requestConfig.verb === 'DELETE' && 
						 event.detail.pathInfo?.requestPath?.match(/^\/admin\/users\/\d+$/));
					
					if (isDeleteRequest) {
						let userEmail = "user";
						
						// Try multiple sources for user email
						if (event.detail.elt && event.detail.elt.getAttribute) {
							userEmail = event.detail.elt.getAttribute('data-user-email') || userEmail;
						}
						
						if (userEmail === "user" && window.lastDeletedUser) {
							userEmail = window.lastDeletedUser.email;
						}
						
						let errorMsg = `Failed to delete user "${userEmail}"`;
						
						if (event.detail.xhr && event.detail.xhr.responseText) {
							errorMsg = `Error: ${event.detail.xhr.responseText}`;
						}
						
						showToast(errorMsg, 'error');
						
						// Clear flags
						window.currentlyDeletingUser = false;
						window.isUserDeleteRequest = false;
						window.lastDeletedUser = null;
						return;
					}
					
					// Generic error handling
					let errorMsg = 'An error occurred';
					
					if (event.detail.xhr && event.detail.xhr.responseText) {
						errorMsg = `Error: ${event.detail.xhr.responseText}`;
					}
					
					showToast(errorMsg, 'error');
				});
			</script>
			
			<!-- Header -->
			<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-users w-6 h-6 mr-2 text-blue-500"></i>
					User Management
				</h1>
				<div class="flex items-center space-x-2">
					<button
						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"
						hx-get="/admin/users/new"
						hx-target="#userManagementContainer"
						hx-push-url="true"
					>
						<i class="fas fa-user-plus w-4 h-4 mr-2"></i>
						Add User
					</button>
				</div>
			</div>
			
			<!-- Check for URL parameters after page load to show success/error messages -->
			<script>
				document.addEventListener('DOMContentLoaded', function() {
					// Get URL parameters
					const urlParams = new URLSearchParams(window.location.search);
					const successMsg = urlParams.get('success');
					const errorMsg = urlParams.get('error');
					
					// Show success toast if parameter exists
					if (successMsg) {
						showToast(decodeURIComponent(successMsg), 'success');
					}
					
					// Show error toast if parameter exists
					if (errorMsg) {
						showToast(decodeURIComponent(errorMsg), 'error');
					}
				});
			</script>
			
			<!-- Convert existing messages to toasts if present -->
			if data.SuccessMessage != "" {
				<script>
					// Show success message as toast
					document.addEventListener('DOMContentLoaded', function() {
						showToast("{ data.SuccessMessage }", 'success');
					});
				</script>
			}
			if data.ErrorMessage != "" {
				<script>
					// Show error message as toast
					document.addEventListener('DOMContentLoaded', function() {
						showToast("{ data.ErrorMessage }", 'error');
					});
				</script>
			}
			
			<!-- Main Content Container -->
			<div class="bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 dark:bg-gray-800">
				<!-- Include the appropriate tab -->
				if data.ActiveTab == "list" || data.ActiveTab == "" {
					@userList(data.Users)
				} else if data.ActiveTab == "create" {
					@userForm(nil, true, data.Roles)
				} else if data.ActiveTab == "edit" && data.EditUser != nil {
					@userForm(data.EditUser, false, data.Roles)
				}
			</div>
			<!-- Help Notice -->
			<div class="mt-8">
				<div class="flex p-4 text-sm text-blue-800 rounded-lg bg-blue-50 dark:bg-blue-900 dark:text-blue-400" role="alert">
					<i class="fas fa-shield-alt flex-shrink-0 inline w-4 h-4 me-3 mt-0.5"></i>
					<span class="sr-only">Info</span>
					<div>
						User accounts provide secure access to the GoMFT application with role-based permissions
					</div>
				</div>
			</div>
		</div>
	</div>
}

// User listing component
templ userList(users []db.User) {
	<!-- Dialog Container for User Actions -->
	for _, user := range users {
		@UserDialog(
			fmt.Sprintf("delete-user-dialog-%d", user.ID),
			"Delete User",
			fmt.Sprintf("Are you sure you want to delete user \"%s\"? This action cannot be undone.", user.Email),
			"bg-red-600 hover:bg-red-700 dark:bg-red-600 dark:hover:bg-red-700",
			"Delete User",
			"delete",
			user.ID,
			user.Email,
		)
	}
	
	<div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 overflow-hidden">
		<div class="overflow-x-auto">
			<table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
				<thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
					<tr>
						<th scope="col" class="px-6 py-3">
							<div class="flex items-center">
								<i class="fas fa-envelope w-4 h-4 mr-1"></i>
								Email
							</div>
						</th>
						<th scope="col" class="px-6 py-3">
							<div class="flex items-center">
								<i class="fas fa-user-tag w-4 h-4 mr-1"></i>
								Role
							</div>
						</th>
						<th scope="col" class="px-6 py-3">
							<div class="flex items-center">
								<i class="fas fa-clock w-4 h-4 mr-1"></i>
								Status
							</div>
						</th>
						<th scope="col" class="px-6 py-3">
							<span class="sr-only">Actions</span>
						</th>
					</tr>
				</thead>
				<tbody>
					if len(users) == 0 {
						<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
							<td colspan="4" class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500 dark:text-gray-400">
								No users found. Click the "Add User" button to create your first user.
							</td>
						</tr>
					} else {
						for _, user := range users {
							<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600">
								<td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
									{ user.Email }
								</td>
								<td class="px-6 py-4">
									if user.GetIsAdmin() {
										<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded-full dark:bg-blue-900 dark:text-blue-300">
											<i class="fas fa-user-shield w-3 h-3 mr-1"></i> Admin
										</span>
									} else {
										<span class="bg-gray-100 text-gray-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded-full dark:bg-gray-700 dark:text-gray-300">
											<i class="fas fa-user w-3 h-3 mr-1"></i> User
										</span>
									}
								</td>
								<td class="px-6 py-4">
									if user.GetAccountLocked() {
										<span class="bg-red-100 text-red-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded-full dark:bg-red-900 dark:text-red-300">
											<i class="fas fa-lock w-3 h-3 mr-1"></i> Locked
										</span>
									} else {
										<span class="bg-green-100 text-green-800 text-xs font-medium me-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"></i> Active
										</span>
									}
								</td>
								<td class="px-6 py-4 text-right">
									<button
										class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center me-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
										hx-get={ "/admin/users/" + strconv.Itoa(int(user.ID)) + "/edit" }
										hx-target="#userManagementContainer"
										hx-push-url="true"
									>
										<i class="fas fa-edit w-3.5 h-3.5 mr-1.5"></i> Edit
									</button>
									<button
										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"
										data-user-email={ user.Email }
										data-user-id={ strconv.Itoa(int(user.ID)) }
										onclick={ showUserDialog(fmt.Sprintf("delete-user-dialog-%d", user.ID)) }
									>
										<i class="fas fa-trash-alt w-3.5 h-3.5 mr-1.5"></i> Delete
									</button>
								</td>
							</tr>
						}
					}
				</tbody>
			</table>
		</div>
	</div>
}

// User form component for creating/editing users
templ userForm(user *db.User, isNew bool, availableRoles []db.Role) {
	<div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 overflow-hidden">
		<div class="p-6">
			<div class="mb-6">
				<h3 class="text-lg font-medium leading-none text-gray-900 dark:text-white">
					if isNew {
						Create New User
					} else {
						Edit User: { user.Email }
					}
				</h3>
				<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
					if isNew {
						Create a new user account with appropriate permissions.
					} else {
						Update user information and permissions.
					}
				</p>
			</div>
			<form
				class="space-y-4 md:space-y-6"
				if isNew {
					hx-post="/admin/users"
				} else {
					hx-put={ "/admin/users/" + strconv.Itoa(int(user.ID)) }
				}
				hx-target="#userManagementContainer"
				x-data="{ 
					password: '',
					confirmPassword: '',
					isAdmin: false,
					passwordsMatch() {
						return this.password === this.confirmPassword || this.confirmPassword === '';
					}
				}"
			>
				<div class="space-y-4">
					<div>
						<label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Email</label>
						<input
							type="email"
							name="email"
							id="email"
							required
							class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
							placeholder="user@example.com"
							if !isNew {
								value={ user.Email }
							}
						/>
					</div>
					<div>
						<label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
							if isNew {
								Password
							} else {
								New Password (leave blank to keep current)
							}
						</label>
						<input
							type="password"
							name="password"
							id="password"
							x-model="password"
							class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
							placeholder="••••••••"
							if isNew {
								required="true"
							}
						/>
					</div>
					<div>
						<label for="password_confirm" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Confirm Password</label>
						<input
							type="password"
							name="password_confirm"
							id="password_confirm"
							x-model="confirmPassword"
							class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
							placeholder="••••••••"
							if isNew {
								required="true"
							}
						/>
						<p class="mt-1 text-sm text-red-600 dark:text-red-500" x-show="!passwordsMatch() && confirmPassword !== ''">
							Passwords do not match
						</p>
					</div>
					<div class="pt-2">
						<div class="flex items-start">
							<div class="flex items-center h-5">
								<input
									id="is_admin"
									name="is_admin"
									type="checkbox"
									class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800"
									if !isNew && user.GetIsAdmin() {
										checked="true"
									}
								/>
							</div>
							<div class="ml-3 text-sm">
								<label for="is_admin" class="font-medium text-gray-900 dark:text-white">Administrator</label>
								<p class="text-xs font-normal text-gray-500 dark:text-gray-400">Grant administrative privileges to this user</p>
							</div>
						</div>
					</div>
					if !isNew {
						<div class="border-t border-gray-200 dark:border-gray-700 pt-4 mt-4">
							<h4 class="text-base font-medium text-gray-900 dark:text-white mb-2">Account Status</h4>
							<div class="flex items-start">
								<div class="flex items-center h-5">
									<input
										id="account_locked"
										name="account_locked"
										type="checkbox"
										class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800"
										if user.GetAccountLocked() {
											checked="true"
										}
									/>
								</div>
								<div class="ml-3 text-sm">
									<label for="account_locked" class="font-medium text-gray-900 dark:text-white">Lock Account</label>
									<p class="text-xs font-normal text-gray-500 dark:text-gray-400">Prevent user from logging in</p>
								</div>
							</div>
						</div>
					}
					if len(availableRoles) > 0 {
						<div class="border-t border-gray-200 dark:border-gray-700 pt-4 mt-4">
							<h4 class="text-base font-medium text-gray-900 dark:text-white mb-2">Roles</h4>
							<div class="space-y-2">
								for _, role := range availableRoles {
									<div class="flex items-start">
										<div class="flex items-center h-5">
											<input
												id={ "role_" + strconv.Itoa(int(role.ID)) }
												name="roles[]"
												value={ strconv.Itoa(int(role.ID)) }
												type="checkbox"
												class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800"
												if !isNew && hasRole(user, role.ID) {
													checked="true"
												}
											/>
										</div>
										<div class="ml-3 text-sm">
											<label for={ "role_" + strconv.Itoa(int(role.ID)) } class="font-medium text-gray-900 dark:text-white">{ role.Name }</label>
											<p class="text-xs font-normal text-gray-500 dark:text-gray-400">{ role.Description }</p>
										</div>
									</div>
								}
							</div>
						</div>
					}
				</div>
				<div class="flex items-center justify-between pt-4 border-t border-gray-200 dark:border-gray-700">
					<button
						type="button"
						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"
						hx-get="/admin/users"
						hx-target="#userManagementContainer"
						hx-push-url="true"
					>
						<i class="fas fa-arrow-left mr-2"></i>
						Cancel
					</button>
					<button
						type="submit"
						class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
						x-bind:disabled="!passwordsMatch() && confirmPassword !== ''"
					>
						<i class="fas fa-save mr-2"></i>
						if isNew {
							Create User
						} else {
							Update User
						}
					</button>
				</div>
			</form>
		</div>
	</div>
}

// Helper function to check if a user has a specific role
func hasRole(user *db.User, roleID uint) bool {
	for _, role := range user.Roles {
		if role.ID == roleID {
			return true
		}
	}
	return false
}

// UserDialog for confirmation actions
templ UserDialog(id string, title string, message string, confirmClass string, confirmText string, action string, userID uint, userEmail 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-user-slash 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="text-white font-medium rounded-lg text-sm px-5 py-2.5 text-center me-2 bg-red-600 hover:bg-red-700 focus:ring-4 focus:outline-none focus:ring-red-300 dark:bg-red-500 dark:hover:bg-red-600 dark:focus:ring-red-800"
						hx-delete={ fmt.Sprintf("/admin/users/%d", userID) }
						hx-target="#userManagementContainer"
						data-user-email={ userEmail }
						id={ fmt.Sprintf("delete-user-btn-%d", userID) }
						onclick={ triggerUserDelete(id, userID, userEmail) }>
						{ 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 hideUserDialog(id string) {
	document.getElementById(id).classList.add("hidden");
	document.getElementById(id).classList.remove("flex");
}

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

script triggerUserDelete(dialogId string, userID uint, userEmail 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.lastDeletedUser = {
		id: userID,
		email: userEmail
	};

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