package components

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

// formatTime formats a time.Time value as a human-readable string
func formatTime(t time.Time) string {
	return t.Format("Jan 02, 2006 15:04")
}

templ AuthProviders(ctx context.Context, providers []db.AuthProvider) {
	@LayoutWithContext("Authentication Providers", ctx) {
		<!-- Toast container for notifications -->
		<div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-2"></div>

		<div id="auth-providers-container" style="min-height: 100vh; background-color: rgb(249, 250, 251);" class="auth-providers-page bg-gray-50 dark:bg-gray-900">
			<div class="p-4 pb-8 w-full">
				<div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
					<div>
						<h1 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center">
							<i class="fas fa-user-shield w-6 h-6 mr-2 text-blue-500 dark:text-blue-400"></i>
							Authentication Providers
						</h1>
						<p class="text-gray-500 dark:text-gray-400">Manage external authentication sources like Authentik, OIDC, SAML, etc.</p>
					</div>
					<div>
						<a href="/admin/settings/auth-providers/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 Provider
						</a>
					</div>
				</div>

				<div class="mt-6">
					if len(providers) > 0 {
						<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 rtl:text-right">
									<thead class="text-xs uppercase bg-gray-100 dark:bg-gray-700">
										<tr>
											<th scope="col" class="px-6 py-3">Name</th>
											<th scope="col" class="px-6 py-3">Icon</th>
											<th scope="col" class="px-6 py-3">Type</th>
											<th scope="col" class="px-6 py-3">Status</th>
											<th scope="col" class="px-6 py-3">Provider URL</th>
											<th scope="col" class="px-6 py-3">Last Used</th>
											<th scope="col" class="px-6 py-3">Actions</th>
										</tr>
									</thead>
									<tbody>
										for _, provider := range providers {
											<tr class="border-b border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50">
												<td class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
													{ provider.Name }
												</td>
												<td class="px-6 py-4">
													<div class="flex items-center justify-center">
														if provider.IconURL != "" {
															<img src={ provider.IconURL } class="w-6 h-6" alt={ provider.Name + " icon" } />
														} else {
															if provider.Type == db.ProviderTypeAuthentik {
																<img src="/static/img/authentik.svg" class="w-6 h-6" alt="Authentik" />
															} else if provider.Type == db.ProviderTypeOIDC {
																<img src="/static/img/oidc.svg" class="w-6 h-6" alt="OIDC" />
															} else if provider.Type == db.ProviderTypeSAML {
																<img src="/static/img/saml.svg" class="w-6 h-6" alt="SAML" />
															} else if provider.Type == db.ProviderTypeOAuth2 {
																<img src="/static/img/oauth2.svg" class="w-6 h-6" alt="OAuth2" />
															} else {
																<i class="fas fa-user-shield text-blue-500 text-lg"></i>
															}
														}
													</div>
												</td>
												<td class="px-6 py-4 uppercase">
													{ string(provider.Type) }
												</td>
												<td class="px-6 py-4">
													if provider.Enabled {
														<span class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">
															Active
														</span>
													} else {
														<span class="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">
															Disabled
														</span>
													}
												</td>
												<td class="px-6 py-4 max-w-[200px] truncate">
													{ provider.ProviderURL }
												</td>
												<td class="px-6 py-4">
													if provider.LastUsed.Valid {
														{ formatTime(provider.LastUsed.Time) }
													} else {
														<span class="text-gray-400 dark:text-gray-500">Never</span>
													}
												</td>
												<td class="px-6 py-4">
													<div class="flex gap-2">
														<a href={ templ.SafeURL("/admin/settings/auth-providers/" + fmt.Sprint(provider.ID) + "/edit") } 
														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"
														title="Edit">
															<i class="fas fa-edit w-3.5 h-3.5 mr-1.5"></i>
															Edit
														</a>
														<button
															type="button"
															data-provider-id={ fmt.Sprint(provider.ID) }
															data-provider-name={ provider.Name }
															class="delete-provider-btn 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"
															title="Delete">
															<i class="fas fa-trash-alt w-3.5 h-3.5 mr-1.5"></i>
															Delete
														</button>
														<button
															data-provider-id={ fmt.Sprint(provider.ID) }
															onclick="testProvider(this)"
															class="text-blue-700 bg-blue-100 hover:bg-blue-200 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 dark:bg-blue-700 dark:text-blue-300 dark:hover:bg-blue-600 dark:focus:ring-blue-800"
															title="Test Connection">
															<i class="fas fa-check-circle w-3.5 h-3.5 mr-1.5"></i>
															Test
														</button>
													</div>
												</td>
											</tr>
										}
									</tbody>
								</table>
							</div>
						</div>
					} else {
						<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-user-shield 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 Authentication Providers</h3>
							<p class="text-gray-500 dark:text-gray-400 mb-4">
								You haven't set up any external authentication providers yet.
							</p>
							<a href="/admin/settings/auth-providers/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 Provider
							</a>
						</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">Authentication providers allow users to sign in using external identity providers.</p>
						</div>
					</div>

					<div class="flex items-start mt-4">
						<div class="flex items-center h-5">
							<i class="fas fa-key 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">Make sure to configure callback URLs in your provider's settings.</p>
						</div>
					</div>

					<div class="flex items-start mt-4">
						<div class="flex items-center h-5">
							<i class="fas fa-user-check 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">Test your connections to ensure proper communication with external authentication systems.</p>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- Delete Provider Modal using Flowbite style -->
		<div id="deleteProviderModal" 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">
						<i class="fas fa-trash-alt text-red-400 text-3xl mb-4"></i>
						<h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">Are you sure you want to delete the provider <strong id="providerNameConfirm"></strong>?</h3>
						<button 
							type="button" 
							id="confirmDeleteBtn"
							class="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
						</button>
						<button type="button" onclick="closeDeleteModal()" 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>
			// Toast notification function
			function showToast(type, message) {
				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);
			}

			function confirmDeleteProvider(providerId, providerName) {
				document.getElementById('providerNameConfirm').textContent = providerName;
				document.getElementById('confirmDeleteBtn').onclick = () => deleteProvider(providerId);
				
				// Show the modal
				document.getElementById('deleteProviderModal').classList.remove('hidden');
				document.getElementById('deleteProviderModal').classList.add('flex');
			}
			
			function closeDeleteModal() {
				document.getElementById('deleteProviderModal').classList.add('hidden');
				document.getElementById('deleteProviderModal').classList.remove('flex');
			}
			
			function deleteProvider(providerId) {
				fetch(`/admin/settings/auth-providers/${providerId}`, {
					method: 'DELETE',
					headers: {
						'Content-Type': 'application/json',
					},
				})
				.then(response => response.json())
				.then(data => {
					if (data.error) {
						showToast('error', data.error);
					} else {
						showToast('success', 'Authentication provider deleted successfully');
						setTimeout(() => {
							window.location.reload();
						}, 1000);
					}
					closeDeleteModal();
				})
				.catch(error => {
					console.error('Error:', error);
					showToast('error', 'Failed to delete authentication provider');
					closeDeleteModal();
				});
			}
			
			function testProvider(btn) {
				const providerId = btn.getAttribute('data-provider-id');
				const originalText = btn.innerHTML;
				btn.disabled = true;
				btn.innerHTML = '<i class="fas fa-spinner fa-spin w-3.5 h-3.5 mr-1.5"></i> Testing...';
				
				fetch(`/admin/settings/auth-providers/${providerId}/test`, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
					},
				})
				.then(response => response.json())
				.then(data => {
					if (data.error) {
						showToast('error', data.error);
					} else if (data.success) {
						showToast('success', data.message || 'Connection test successful');
					} else {
						showToast('error', 'Connection test failed');
					}
					
					btn.disabled = false;
					btn.innerHTML = originalText;
				})
				.catch(error => {
					console.error('Error:', error);
					showToast('error', 'Connection test failed');
					
					btn.disabled = false;
					btn.innerHTML = originalText;
				});
			}
			
			// Set dark background color if in dark mode
			document.addEventListener('DOMContentLoaded', function() {
				if (document.documentElement.classList.contains('dark')) {
					document.getElementById('auth-providers-container').style.backgroundColor = '#111827';
				}
				
				// Add event listener for theme changes
				const themeToggle = document.getElementById('theme-toggle');
				if (themeToggle) {
					themeToggle.addEventListener('click', function() {
						setTimeout(function() {
							const isDark = document.documentElement.classList.contains('dark');
							document.getElementById('auth-providers-container').style.backgroundColor = isDark ? '#111827' : 'rgb(249, 250, 251)';
						}, 50);
					});
				}
				
				// Set up event listeners for delete buttons
				document.querySelectorAll('.delete-provider-btn').forEach(button => {
					button.addEventListener('click', function() {
						const providerId = this.getAttribute('data-provider-id');
						const providerName = this.getAttribute('data-provider-name');
						confirmDeleteProvider(providerId, providerName);
					});
				});
			});
		</script>
	}
} 