<script lang="ts">
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import {
		Mail,
		X,
		Save,
		Eye,
		ArrowLeft,
		Search,
		CheckCircle,
		XCircle,
		Loader2,
		FileText,
		Variable
	} from 'lucide-svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';

	interface EmailTemplate {
		template_key: string;
		template_name: string;
		category: string;
		subject: string;
		body_html: string;
		body_text: string;
		is_active: boolean;
		is_system: boolean;
		variables_schema: Record<string, string> | null;
		updated_at: string | null;
	}

	let { data, form } = $props();
	const templates = $derived(data.templates as EmailTemplate[]);

	// UI State
	let selectedCategory = $state<string>('all');
	let searchQuery = $state('');
	let editingTemplate = $state<EmailTemplate | null>(null);
	let showPreview = $state(false);
	let isSubmitting = $state(false);

	// Edit form state
	let editSubject = $state('');
	let editBodyHtml = $state('');
	let editBodyText = $state('');
	let editIsActive = $state(true);

	// Track which field is active for variable insertion
	let activeField = $state<'subject' | 'body_html' | 'body_text'>('subject');

	// Element refs
	let subjectInput: HTMLInputElement;
	let bodyHtmlTextarea: HTMLTextAreaElement;
	let bodyTextTextarea: HTMLTextAreaElement;

	// Sample data for preview
	const sampleData: Record<string, string> = {
		first_name: 'John',
		last_name: 'Doe',
		email: 'john.doe@example.com',
		member_id: 'MUSA-0001',
		portal_url: 'https://portal.monacousa.org',
		amount: '$150.00',
		due_date: 'February 15, 2026',
		event_title: 'Monaco National Day Celebration',
		event_date: 'November 19, 2026',
		event_time: '6:00 PM',
		event_location: 'The Monaco Club, New York',
		guest_count: '2',
		reset_link: 'https://portal.monacousa.org/reset-password?token=abc123',
		verification_link: 'https://portal.monacousa.org/verify?token=abc123'
	};

	// Get unique categories
	const categories = $derived.by(() => {
		const cats = new Set(templates.map(t => t.category));
		return ['all', ...Array.from(cats).sort()];
	});

	// Group templates by category
	const templatesByCategory = $derived.by(() => {
		return templates.reduce((acc, t) => {
			const cat = t.category || 'other';
			if (!acc[cat]) acc[cat] = [];
			acc[cat].push(t);
			return acc;
		}, {} as Record<string, EmailTemplate[]>);
	});

	// Filtered templates
	const filteredTemplates = $derived.by(() => {
		let result = templates;

		if (selectedCategory !== 'all') {
			result = result.filter(t => t.category === selectedCategory);
		}

		if (searchQuery.trim()) {
			const query = searchQuery.toLowerCase();
			result = result.filter(t =>
				t.template_name.toLowerCase().includes(query) ||
				t.template_key.toLowerCase().includes(query) ||
				t.subject.toLowerCase().includes(query)
			);
		}

		return result;
	});

	// Get variables for the current template
	const templateVariables = $derived.by(() => {
		if (!editingTemplate?.variables_schema) return [];
		return Object.entries(editingTemplate.variables_schema);
	});

	// Format category name
	function formatCategory(cat: string): string {
		return cat.charAt(0).toUpperCase() + cat.slice(1).replace(/_/g, ' ');
	}

	// Open edit modal
	function openEditor(template: EmailTemplate) {
		editingTemplate = template;
		editSubject = template.subject;
		editBodyHtml = template.body_html;
		editBodyText = template.body_text;
		editIsActive = template.is_active;
		showPreview = false;
		activeField = 'subject';
	}

	// Close edit modal
	function closeEditor() {
		editingTemplate = null;
		showPreview = false;
	}

	// Insert variable at cursor position
	function insertVariable(varName: string) {
		const tag = `{{${varName}}}`;

		if (activeField === 'subject' && subjectInput) {
			const start = subjectInput.selectionStart ?? editSubject.length;
			const end = subjectInput.selectionEnd ?? editSubject.length;
			editSubject = editSubject.slice(0, start) + tag + editSubject.slice(end);
			// Restore focus and cursor position
			setTimeout(() => {
				subjectInput.focus();
				subjectInput.setSelectionRange(start + tag.length, start + tag.length);
			}, 0);
		} else if (activeField === 'body_html' && bodyHtmlTextarea) {
			const start = bodyHtmlTextarea.selectionStart ?? editBodyHtml.length;
			const end = bodyHtmlTextarea.selectionEnd ?? editBodyHtml.length;
			editBodyHtml = editBodyHtml.slice(0, start) + tag + editBodyHtml.slice(end);
			setTimeout(() => {
				bodyHtmlTextarea.focus();
				bodyHtmlTextarea.setSelectionRange(start + tag.length, start + tag.length);
			}, 0);
		} else if (activeField === 'body_text' && bodyTextTextarea) {
			const start = bodyTextTextarea.selectionStart ?? editBodyText.length;
			const end = bodyTextTextarea.selectionEnd ?? editBodyText.length;
			editBodyText = editBodyText.slice(0, start) + tag + editBodyText.slice(end);
			setTimeout(() => {
				bodyTextTextarea.focus();
				bodyTextTextarea.setSelectionRange(start + tag.length, start + tag.length);
			}, 0);
		}
	}

	// Render preview with sample data (content only)
	function renderPreview(html: string): string {
		let result = html;
		for (const [key, value] of Object.entries(sampleData)) {
			result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
		}
		// Also replace any remaining variables with placeholder
		result = result.replace(/\{\{(\w+)\}\}/g, '<span style="color: #d97706; background: #fef3c7; padding: 2px 4px; border-radius: 4px;">[[$1]]</span>');
		return result;
	}

	// Generate full email HTML preview
	// If template already has full HTML wrapper (legacy templates), render directly
	// Otherwise wrap with Monaco template
	function generateFullEmailPreview(subject: string, bodyHtml: string): string {
		const renderedBody = renderPreview(bodyHtml);

		// Check if template already has full HTML wrapper (legacy templates)
		const hasFullWrapper = bodyHtml.includes('<!DOCTYPE') || bodyHtml.includes('<html');

		if (hasFullWrapper) {
			// Template has its own HTML structure - render as-is with variables replaced
			// Also inject background image URL for S3
			let html = renderedBody;
			// Update background image URL if using old gradient-only style
			html = html.replace(
				/background:\s*linear-gradient\([^)]+\);\s*background-color:\s*#0f172a;/g,
				"background-image: url('https://s3.monacousa.org/public/monaco_high_res.jpg'); background-size: cover; background-position: center; background-color: #0f172a;"
			);
			// Fix logo URL for preview
			html = html.replace(/\{\{logo_url\}\}/g, '/MONACOUSA-Flags_376x376.png');
			return html;
		}

		// Content-only template - wrap with Monaco template
		const renderedSubject = renderPreview(subject);
		const logoUrl = '/MONACOUSA-Flags_376x376.png';
		const bgImageUrl = 'https://s3.monacousa.org/public/monaco_high_res.jpg';
		const emailTitle = renderedSubject.replace(/<[^>]*>/g, '').trim() || 'Email Preview';

		return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body { margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #0f172a; }
  </style>
</head>
<body>
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-image: url('${bgImageUrl}'); background-size: cover; background-position: center; background-color: #0f172a;">
    <tr>
      <td>
        <div style="background: linear-gradient(135deg, rgba(15, 23, 42, 0.8) 0%, rgba(15, 23, 42, 0.6) 50%, rgba(127, 29, 29, 0.7) 100%);">
          <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
            <tr>
              <td align="center" style="padding: 40px 20px;">
                <!-- Logo Section -->
                <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width: 480px;">
                  <tr>
                    <td align="center" style="padding-bottom: 30px;">
                      <div style="background: rgba(255, 255, 255, 0.95); border-radius: 16px; padding: 12px; display: inline-block; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);">
                        <img src="${logoUrl}" alt="Monaco USA" width="80" height="80" style="display: block; border-radius: 8px;">
                      </div>
                      <h1 style="margin: 16px 0 4px 0; font-size: 24px; font-weight: bold; color: #ffffff; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);">Monaco <span style="color: #fca5a5;">USA</span></h1>
                      <p style="margin: 0; font-size: 14px; color: rgba(255, 255, 255, 0.8);">Americans in Monaco</p>
                    </td>
                  </tr>
                </table>

                <!-- Main Content Card -->
                <table role="presentation" cellspacing="0" cellpadding="0" style="max-width: 480px; width: 100%; background: #ffffff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);">
                  <tr>
                    <td style="padding: 40px;">
                      <h2 style="margin: 0 0 20px 0; color: #CE1126; font-size: 24px; text-align: center;">${emailTitle}</h2>
                      <div style="text-align: left;">${renderedBody}</div>
                    </td>
                  </tr>
                </table>

                <!-- Footer -->
                <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width: 480px;">
                  <tr>
                    <td align="center" style="padding-top: 24px;">
                      <p style="margin: 0; font-size: 12px; color: rgba(255, 255, 255, 0.5);">&copy; 2026 Monaco USA. All rights reserved.</p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
        </div>
      </td>
    </tr>
  </table>
</body>
</html>`;
	}

	// Get preview HTML as data URL for iframe
	const previewDataUrl = $derived.by(() => {
		if (!showPreview || !editingTemplate) return '';
		const html = generateFullEmailPreview(editSubject, editBodyHtml);
		return 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
	});

	// Get category color
	function getCategoryColor(cat: string): string {
		const colors: Record<string, string> = {
			auth: 'bg-blue-100 text-blue-700',
			payment: 'bg-green-100 text-green-700',
			events: 'bg-purple-100 text-purple-700',
			membership: 'bg-amber-100 text-amber-700',
			other: 'bg-slate-100 text-slate-700'
		};
		return colors[cat] || colors.other;
	}
</script>

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

<div class="space-y-6">
	<!-- Header -->
	<div class="flex items-center justify-between">
		<div class="flex items-center gap-4">
			<a
				href="/admin/settings"
				class="inline-flex items-center gap-2 text-sm font-medium text-slate-600 hover:text-monaco-600"
			>
				<ArrowLeft class="h-4 w-4" />
				Back to Settings
			</a>
		</div>
	</div>

	<div>
		<h1 class="text-2xl font-bold text-slate-900">Email Templates</h1>
		<p class="text-slate-500">Edit the text content of email notifications sent by the system</p>
	</div>

	<!-- Success/Error Messages -->
	{#if form?.success}
		<div class="flex items-center gap-2 rounded-lg bg-green-50 border border-green-200 p-4 text-green-700">
			<CheckCircle class="h-5 w-5 shrink-0" />
			<span>{form.message || 'Template updated successfully'}</span>
		</div>
	{/if}

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

	<!-- Filters -->
	<div class="glass-card p-4">
		<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
			<!-- Category Filter -->
			<div class="flex items-center gap-2">
				<Label for="category" class="text-sm font-medium text-slate-700">Category:</Label>
				<select
					id="category"
					bind:value={selectedCategory}
					class="h-9 rounded-lg border border-slate-200 bg-white px-3 text-sm focus:border-monaco-500 focus:outline-none focus:ring-2 focus:ring-monaco-500/20"
				>
					{#each categories as cat}
						<option value={cat}>{cat === 'all' ? 'All Categories' : formatCategory(cat)}</option>
					{/each}
				</select>
			</div>

			<!-- Search -->
			<div class="relative flex-1 sm:max-w-xs">
				<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
				<Input
					type="text"
					placeholder="Search templates..."
					bind:value={searchQuery}
					class="h-9 pl-9"
				/>
			</div>
		</div>
	</div>

	<!-- Template Grid -->
	<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
		{#each filteredTemplates as template}
			<div class="glass-card p-5 hover:shadow-md transition-shadow">
				<div class="flex items-start justify-between gap-3">
					<div class="flex-1 min-w-0">
						<div class="flex items-center gap-2 mb-2">
							<span class="rounded-full px-2.5 py-0.5 text-xs font-medium {getCategoryColor(template.category)}">
								{formatCategory(template.category)}
							</span>
							{#if !template.is_active}
								<span class="rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium text-slate-500">
									Inactive
								</span>
							{/if}
						</div>
						<h3 class="font-semibold text-slate-900 truncate">{template.template_name}</h3>
						<p class="mt-1 text-sm text-slate-500 truncate">{template.subject}</p>
					</div>
					<Mail class="h-5 w-5 shrink-0 text-slate-400" />
				</div>
				<div class="mt-4 flex items-center justify-between">
					<span class="text-xs text-slate-400">{template.template_key}</span>
					<Button
						variant="outline"
						size="sm"
						onclick={() => openEditor(template)}
					>
						Edit
					</Button>
				</div>
			</div>
		{:else}
			<div class="col-span-full glass-card p-12 text-center">
				<FileText class="mx-auto h-12 w-12 text-slate-300" />
				<p class="mt-4 text-slate-500">No templates found</p>
			</div>
		{/each}
	</div>
</div>

<!-- Edit Modal -->
{#if editingTemplate}
	<div
		class="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 p-4 backdrop-blur-sm"
		onclick={(e) => { if (e.target === e.currentTarget) closeEditor(); }}
		onkeydown={(e) => { if (e.key === 'Escape') closeEditor(); }}
		role="dialog"
		aria-modal="true"
		tabindex="-1"
	>
		<div class="my-8 w-full max-w-4xl rounded-2xl bg-white shadow-2xl">
			<!-- Modal Header -->
			<div class="flex items-center justify-between border-b border-slate-200 px-6 py-4">
				<div>
					<h2 class="text-xl font-semibold text-slate-900">Edit: {editingTemplate.template_name}</h2>
					<p class="text-sm text-slate-500">{editingTemplate.template_key}</p>
				</div>
				<button
					onclick={closeEditor}
					class="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
				>
					<X class="h-5 w-5" />
				</button>
			</div>

			<!-- Modal Body -->
			<form
				method="POST"
				action="?/updateTemplate"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						isSubmitting = false;
						if (result.type === 'success') {
							await invalidateAll();
							closeEditor();
						}
						await update();
					};
				}}
				class="p-6 space-y-6"
			>
				<input type="hidden" name="template_key" value={editingTemplate.template_key} />

				<!-- Subject Line -->
				<div class="space-y-2">
					<Label for="subject">Subject Line</Label>
					<Input
						id="subject"
						name="subject"
						type="text"
						bind:value={editSubject}
						bind:this={subjectInput}
						onfocus={() => activeField = 'subject'}
						class="h-11 font-mono text-sm"
					/>
				</div>

				<!-- Variables Panel -->
				{#if templateVariables.length > 0}
					<div class="rounded-lg border border-slate-200 bg-slate-50 p-4">
						<div class="flex items-center gap-2 mb-3">
							<Variable class="h-4 w-4 text-slate-600" />
							<span class="text-sm font-medium text-slate-700">Available Variables</span>
							<span class="text-xs text-slate-500">(click to insert at cursor)</span>
						</div>
						<div class="flex flex-wrap gap-2">
							{#each templateVariables as [varName, description]}
								<button
									type="button"
									onclick={() => insertVariable(varName)}
									class="inline-flex items-center gap-1 rounded-md border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-mono text-slate-700 hover:bg-monaco-50 hover:border-monaco-300 hover:text-monaco-700 transition-colors"
									title={description}
								>
									{`{{${varName}}}`}
								</button>
							{/each}
						</div>
					</div>
				{/if}

				<!-- Body HTML -->
				<div class="space-y-2">
					<div class="flex items-center justify-between">
						<Label for="body_html">Email Body (HTML)</Label>
						<button
							type="button"
							onclick={() => showPreview = !showPreview}
							class="inline-flex items-center gap-1.5 text-sm text-monaco-600 hover:text-monaco-700"
						>
							<Eye class="h-4 w-4" />
							{showPreview ? 'Edit' : 'Preview'}
						</button>
					</div>
					{#if showPreview}
						<div class="rounded-lg border border-slate-200 bg-slate-900 overflow-hidden" style="min-height: 500px;">
							<div class="bg-slate-800 px-4 py-2 border-b border-slate-700">
								<p class="text-xs text-slate-400">Subject: <span class="text-white font-medium">{renderPreview(editSubject)}</span></p>
							</div>
							<iframe
								src={previewDataUrl}
								title="Email Preview"
								class="w-full border-0"
								style="height: 600px;"
								sandbox="allow-same-origin"
							></iframe>
						</div>
					{:else}
						<textarea
							id="body_html"
							name="body_html"
							bind:value={editBodyHtml}
							bind:this={bodyHtmlTextarea}
							onfocus={() => activeField = 'body_html'}
							rows="12"
							class="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 font-mono text-sm text-slate-900 focus:border-monaco-500 focus:outline-none focus:ring-2 focus:ring-monaco-500/20 resize-y"
						></textarea>
					{/if}
				</div>

				<!-- Body Text -->
				<div class="space-y-2">
					<Label for="body_text">Plain Text Version (fallback)</Label>
					<textarea
						id="body_text"
						name="body_text"
						bind:value={editBodyText}
						bind:this={bodyTextTextarea}
						onfocus={() => activeField = 'body_text'}
						rows="6"
						class="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 font-mono text-sm text-slate-900 focus:border-monaco-500 focus:outline-none focus:ring-2 focus:ring-monaco-500/20 resize-y"
					></textarea>
				</div>

				<!-- Active Toggle -->
				<div class="flex items-center gap-3">
					<label class="relative inline-flex cursor-pointer items-center">
						<input
							type="checkbox"
							bind:checked={editIsActive}
							class="peer sr-only"
						/>
						<input type="hidden" name="is_active" value={editIsActive ? 'true' : 'false'} />
						<div class="peer h-6 w-11 rounded-full bg-slate-200 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white after:transition-all peer-checked:bg-monaco-600 peer-checked:after:translate-x-5"></div>
					</label>
					<span class="text-sm text-slate-700">Template Active</span>
				</div>

				<!-- Footer -->
				<div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-200">
					<Button type="button" variant="outline" onclick={closeEditor} disabled={isSubmitting}>
						Cancel
					</Button>
					<Button type="submit" variant="monaco" disabled={isSubmitting}>
						{#if isSubmitting}
							<Loader2 class="mr-2 h-4 w-4 animate-spin" />
							Saving...
						{:else}
							<Save class="mr-2 h-4 w-4" />
							Save Changes
						{/if}
					</Button>
				</div>
			</form>
		</div>
	</div>
{/if}
