<script lang="ts">
	import {
		Mail,
		Send,
		Eye,
		CheckCircle2,
		XCircle,
		Clock,
		FileText,
		AlertTriangle,
		Loader2,
		X,
		RefreshCw,
		Inbox,
		Settings
	} from 'lucide-svelte';
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';

	let { data, form } = $props();

	const templates = $derived(data.templates);
	const templatesByCategory = $derived(data.templatesByCategory);
	const recentLogs = $derived(data.recentLogs);
	const smtpConfigured = $derived(data.smtpConfigured);
	const adminEmail = $derived(data.adminEmail);

	let selectedTemplate = $state<string>('');
	let recipientEmail = $state(adminEmail || '');
	let customSubject = $state('Test Email from Monaco USA');
	let customMessage = $state('This is a test email sent from the Monaco USA admin panel.');
	let isLoading = $state(false);
	let activeTab = $state<'templates' | 'custom' | 'logs'>('templates');

	// Preview modal state
	let showPreview = $state(false);
	let previewHtml = $state('');
	let previewSubject = $state('');
	let isLoadingPreview = $state(false);

	// Get category display name
	function getCategoryName(category: string): string {
		const names: Record<string, string> = {
			dues: 'Dues & Payments',
			events: 'Events',
			auth: 'Authentication',
			welcome: 'Welcome & Onboarding',
			notifications: 'Notifications',
			other: 'Other'
		};
		return names[category] || category.charAt(0).toUpperCase() + category.slice(1);
	}

	// Get status badge styling
	function getStatusBadge(status: string) {
		switch (status) {
			case 'sent':
				return { color: 'bg-green-100 text-green-700', icon: CheckCircle2 };
			case 'failed':
				return { color: 'bg-red-100 text-red-700', icon: XCircle };
			case 'pending':
				return { color: 'bg-yellow-100 text-yellow-700', icon: Clock };
			default:
				return { color: 'bg-slate-100 text-slate-700', icon: Mail };
		}
	}

	// Format date
	function formatDate(dateStr: string): string {
		return new Date(dateStr).toLocaleString('en-US', {
			month: 'short',
			day: 'numeric',
			hour: 'numeric',
			minute: '2-digit'
		});
	}
</script>

<svelte:head>
	<title>Email Testing | Monaco USA Admin</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div>
			<h1 class="text-2xl font-bold text-slate-900">Email Testing</h1>
			<p class="text-slate-500">Test email notifications across the platform</p>
		</div>
		<a
			href="/admin/settings"
			class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
		>
			<Settings class="h-4 w-4" />
			Email Settings
		</a>
	</div>

	<!-- SMTP Status Banner -->
	{#if !smtpConfigured}
		<div class="rounded-lg border border-amber-200 bg-amber-50 p-4">
			<div class="flex items-start gap-3">
				<AlertTriangle class="h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5" />
				<div>
					<h3 class="font-medium text-amber-800">SMTP Not Configured</h3>
					<p class="mt-1 text-sm text-amber-700">
						Email sending is not configured. Please configure SMTP settings in the
						<a href="/admin/settings" class="underline hover:text-amber-900">Admin Settings</a>
						before testing emails.
					</p>
				</div>
			</div>
		</div>
	{/if}

	<!-- Success/Error Messages -->
	{#if form?.success}
		<div class="rounded-lg border border-green-200 bg-green-50 p-4">
			<div class="flex items-center gap-2 text-green-800">
				<CheckCircle2 class="h-5 w-5" />
				<span class="font-medium">{form.success}</span>
			</div>
		</div>
	{/if}

	{#if form?.error}
		<div class="rounded-lg border border-red-200 bg-red-50 p-4">
			<div class="flex items-center gap-2 text-red-800">
				<XCircle class="h-5 w-5" />
				<span class="font-medium">{form.error}</span>
			</div>
		</div>
	{/if}

	<!-- Tabs -->
	<div class="flex gap-2 border-b border-slate-200">
		<button
			onclick={() => (activeTab = 'templates')}
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'templates'
				? 'border-b-2 border-monaco-600 text-monaco-600'
				: 'text-slate-600 hover:text-slate-900'}"
		>
			<span class="flex items-center gap-2">
				<FileText class="h-4 w-4" />
				Email Templates
			</span>
		</button>
		<button
			onclick={() => (activeTab = 'custom')}
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'custom'
				? 'border-b-2 border-monaco-600 text-monaco-600'
				: 'text-slate-600 hover:text-slate-900'}"
		>
			<span class="flex items-center gap-2">
				<Mail class="h-4 w-4" />
				Custom Email
			</span>
		</button>
		<button
			onclick={() => (activeTab = 'logs')}
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'logs'
				? 'border-b-2 border-monaco-600 text-monaco-600'
				: 'text-slate-600 hover:text-slate-900'}"
		>
			<span class="flex items-center gap-2">
				<Inbox class="h-4 w-4" />
				Recent Logs ({recentLogs.length})
			</span>
		</button>
	</div>

	<!-- Templates Tab -->
	{#if activeTab === 'templates'}
		<div class="grid gap-6 lg:grid-cols-3">
			<!-- Template List -->
			<div class="lg:col-span-2 space-y-4">
				{#each Object.entries(templatesByCategory || {}) as [category, categoryTemplates]}
					<div class="glass-card overflow-hidden">
						<div class="border-b border-slate-200 bg-slate-50 px-4 py-3">
							<h3 class="font-semibold text-slate-900">{getCategoryName(category)}</h3>
						</div>
						<div class="divide-y divide-slate-100">
							{#each categoryTemplates as template}
								<div
									class="flex items-center justify-between p-4 hover:bg-slate-50 cursor-pointer {selectedTemplate === template.template_key ? 'bg-monaco-50 border-l-4 border-monaco-600' : ''}"
									onclick={() => (selectedTemplate = template.template_key)}
									onkeydown={(e) => e.key === 'Enter' && (selectedTemplate = template.template_key)}
									role="button"
									tabindex="0"
								>
									<div class="flex-1 min-w-0">
										<p class="font-medium text-slate-900">{template.name}</p>
										<p class="text-sm text-slate-500 truncate">{template.subject}</p>
									</div>
									<div class="flex items-center gap-2">
										{#if template.is_active}
											<span class="rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
												Active
											</span>
										{:else}
											<span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-500">
												Inactive
											</span>
										{/if}
									</div>
								</div>
							{/each}
						</div>
					</div>
				{/each}

				{#if !templates || templates.length === 0}
					<div class="glass-card p-12 text-center">
						<FileText class="mx-auto h-12 w-12 text-slate-300" />
						<h3 class="mt-4 text-lg font-medium text-slate-900">No Email Templates</h3>
						<p class="mt-2 text-slate-500">
							No email templates have been configured yet.
						</p>
					</div>
				{/if}
			</div>

			<!-- Send Test Panel -->
			<div class="lg:col-span-1">
				<div class="glass-card p-6 sticky top-6">
					<h3 class="font-semibold text-slate-900 mb-4">Send Test Email</h3>

					<form
						method="POST"
						action="?/sendTestTemplate"
						use:enhance={() => {
							isLoading = true;
							return async ({ update }) => {
								isLoading = false;
								await update();
								await invalidateAll();
							};
						}}
						class="space-y-4"
					>
						<div>
							<Label for="recipient_email">Recipient Email</Label>
							<Input
								type="email"
								id="recipient_email"
								name="recipient_email"
								bind:value={recipientEmail}
								placeholder="test@example.com"
								required
								class="mt-1"
							/>
						</div>

						<div>
							<Label for="template_key">Selected Template</Label>
							<select
								id="template_key"
								name="template_key"
								bind:value={selectedTemplate}
								required
								class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
							>
								<option value="">Select a template...</option>
								{#each Object.entries(templatesByCategory || {}) as [category, categoryTemplates]}
									<optgroup label={getCategoryName(category)}>
										{#each categoryTemplates as template}
											<option value={template.template_key}>{template.name}</option>
										{/each}
									</optgroup>
								{/each}
							</select>
						</div>

						<div class="flex gap-2">
							<Button
								type="submit"
								variant="monaco"
								disabled={isLoading || !smtpConfigured || !selectedTemplate}
								class="flex-1"
							>
								{#if isLoading}
									<Loader2 class="mr-2 h-4 w-4 animate-spin" />
									Sending...
								{:else}
									<Send class="mr-2 h-4 w-4" />
									Send Test
								{/if}
							</Button>
						</div>
					</form>

					<!-- Preview Button -->
					{#if selectedTemplate}
						<form
							method="POST"
							action="?/previewTemplate"
							use:enhance={() => {
								isLoadingPreview = true;
								return async ({ result, update }) => {
									isLoadingPreview = false;
									if (result.type === 'success' && result.data?.preview) {
										previewHtml = result.data.preview.html;
										previewSubject = result.data.preview.subject;
										showPreview = true;
									}
									await update();
								};
							}}
							class="mt-4"
						>
							<input type="hidden" name="template_key" value={selectedTemplate} />
							<Button type="submit" variant="outline" disabled={isLoadingPreview} class="w-full">
								{#if isLoadingPreview}
									<Loader2 class="mr-2 h-4 w-4 animate-spin" />
									Loading...
								{:else}
									<Eye class="mr-2 h-4 w-4" />
									Preview Template
								{/if}
							</Button>
						</form>
					{/if}

					<!-- Send All Tests -->
					<div class="mt-6 pt-6 border-t border-slate-200">
						<h4 class="text-sm font-medium text-slate-700 mb-3">Bulk Testing</h4>
						<form
							method="POST"
							action="?/sendAllTests"
							use:enhance={() => {
								if (!confirm(`This will send ALL active email templates to ${recipientEmail}. Continue?`)) {
									return async () => {};
								}
								isLoading = true;
								return async ({ update }) => {
									isLoading = false;
									await update();
									await invalidateAll();
								};
							}}
						>
							<input type="hidden" name="recipient_email" value={recipientEmail} />
							<Button
								type="submit"
								variant="outline"
								disabled={isLoading || !smtpConfigured || !recipientEmail}
								class="w-full border-amber-300 text-amber-700 hover:bg-amber-50"
							>
								<RefreshCw class="mr-2 h-4 w-4" />
								Send All Templates
							</Button>
						</form>
						<p class="mt-2 text-xs text-slate-500">
							Sends all active templates to test the complete notification system.
						</p>
					</div>
				</div>
			</div>
		</div>
	{/if}

	<!-- Custom Email Tab -->
	{#if activeTab === 'custom'}
		<div class="max-w-2xl">
			<div class="glass-card p-6">
				<h3 class="font-semibold text-slate-900 mb-4">Send Custom Test Email</h3>
				<p class="text-sm text-slate-500 mb-6">
					Send a custom email using the Monaco USA branding template.
				</p>

				<form
					method="POST"
					action="?/sendCustomEmail"
					use:enhance={() => {
						isLoading = true;
						return async ({ update }) => {
							isLoading = false;
							await update();
							await invalidateAll();
						};
					}}
					class="space-y-4"
				>
					<div>
						<Label for="custom_recipient">Recipient Email</Label>
						<Input
							type="email"
							id="custom_recipient"
							name="recipient_email"
							bind:value={recipientEmail}
							placeholder="test@example.com"
							required
							class="mt-1"
						/>
					</div>

					<div>
						<Label for="custom_subject">Subject</Label>
						<Input
							type="text"
							id="custom_subject"
							name="subject"
							bind:value={customSubject}
							placeholder="Email subject"
							required
							class="mt-1"
						/>
					</div>

					<div>
						<Label for="custom_message">Message</Label>
						<textarea
							id="custom_message"
							name="message"
							bind:value={customMessage}
							rows="6"
							placeholder="Your message here..."
							required
							class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
						></textarea>
						<p class="mt-1 text-xs text-slate-500">
							The message will be wrapped in the Monaco USA email template.
						</p>
					</div>

					<Button type="submit" variant="monaco" disabled={isLoading || !smtpConfigured}>
						{#if isLoading}
							<Loader2 class="mr-2 h-4 w-4 animate-spin" />
							Sending...
						{:else}
							<Send class="mr-2 h-4 w-4" />
							Send Custom Email
						{/if}
					</Button>
				</form>
			</div>
		</div>
	{/if}

	<!-- Logs Tab -->
	{#if activeTab === 'logs'}
		<div class="glass-card overflow-hidden">
			<div class="border-b border-slate-200 bg-slate-50 px-6 py-4 flex items-center justify-between">
				<h3 class="font-semibold text-slate-900">Recent Email Logs</h3>
				<button
					onclick={() => invalidateAll()}
					class="flex items-center gap-1 text-sm text-slate-600 hover:text-slate-900"
				>
					<RefreshCw class="h-4 w-4" />
					Refresh
				</button>
			</div>

			{#if recentLogs.length === 0}
				<div class="p-12 text-center">
					<Inbox class="mx-auto h-12 w-12 text-slate-300" />
					<h3 class="mt-4 text-lg font-medium text-slate-900">No Email Logs</h3>
					<p class="mt-2 text-slate-500">No emails have been sent yet.</p>
				</div>
			{:else}
				<div class="overflow-x-auto">
					<table class="w-full">
						<thead class="bg-slate-50 border-b border-slate-200">
							<tr>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Recipient</th>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Subject</th>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Type</th>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Sent</th>
								<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">By</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-slate-100">
							{#each recentLogs as log}
								{@const statusBadge = getStatusBadge(log.status)}
								<tr class="hover:bg-slate-50">
									<td class="px-6 py-4">
										<span class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium {statusBadge.color}">
											<svelte:component this={statusBadge.icon} class="h-3 w-3" />
											{log.status}
										</span>
									</td>
									<td class="px-6 py-4">
										<div>
											<p class="text-sm text-slate-900">{log.recipient_email}</p>
											{#if log.recipient_name}
												<p class="text-xs text-slate-500">{log.recipient_name}</p>
											{/if}
										</div>
									</td>
									<td class="px-6 py-4">
										<p class="text-sm text-slate-900 max-w-xs truncate" title={log.subject}>
											{log.subject}
										</p>
									</td>
									<td class="px-6 py-4">
										<span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600">
											{log.email_type || 'manual'}
										</span>
									</td>
									<td class="px-6 py-4 text-sm text-slate-500">
										{log.sent_at ? formatDate(log.sent_at) : formatDate(log.created_at)}
									</td>
									<td class="px-6 py-4 text-sm text-slate-500">
										{#if log.sender}
											{log.sender.first_name} {log.sender.last_name}
										{:else}
											System
										{/if}
									</td>
								</tr>
								{#if log.status === 'failed' && log.error_message}
									<tr class="bg-red-50">
										<td colspan="6" class="px-6 py-2">
											<p class="text-xs text-red-600">
												<strong>Error:</strong> {log.error_message}
											</p>
										</td>
									</tr>
								{/if}
							{/each}
						</tbody>
					</table>
				</div>
			{/if}
		</div>
	{/if}
</div>

<!-- Preview Modal -->
{#if showPreview}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="w-full max-w-4xl max-h-[90vh] flex flex-col rounded-2xl bg-white shadow-xl">
			<div class="flex items-center justify-between border-b border-slate-200 px-6 py-4">
				<div>
					<h3 class="font-semibold text-slate-900">Email Preview</h3>
					<p class="text-sm text-slate-500">{previewSubject}</p>
				</div>
				<button
					onclick={() => (showPreview = false)}
					class="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
				>
					<X class="h-5 w-5" />
				</button>
			</div>
			<div class="flex-1 overflow-auto p-4 bg-slate-100">
				<div class="mx-auto max-w-lg">
					{@html previewHtml}
				</div>
			</div>
			<div class="border-t border-slate-200 px-6 py-4">
				<Button variant="outline" onclick={() => (showPreview = false)}>
					Close Preview
				</Button>
			</div>
		</div>
	</div>
{/if}
