<script lang="ts">
	import DynamicIcon from '$lib/components/ui/DynamicIcon.svelte';

	interface TemplateSection {
		readonly title: string;
		readonly icon: string | null;
		readonly order: number;
	}

	interface Template {
		readonly id: string;
		readonly name: string;
		readonly description: string | null;
		readonly icon: string | null;
		readonly config: {
			readonly sections: readonly TemplateSection[];
		};
		readonly isBuiltin: boolean;
	}

	interface Props {
		onSelect: (templateId: string | null) => void;
	}

	let { onSelect }: Props = $props();

	let templates = $state<Template[]>([]);
	let loading = $state(true);
	let errorMsg = $state<string | null>(null);
	let selected = $state<string | null>(null);
	let importing = $state(false);

	async function loadTemplates() {
		loading = true;
		errorMsg = null;

		try {
			const res = await fetch('/api/templates');
			const json = await res.json();

			if (json.success && Array.isArray(json.data)) {
				templates = json.data;
			} else {
				errorMsg = json.error ?? 'Failed to load templates';
			}
		} catch {
			errorMsg = 'Failed to load templates';
		} finally {
			loading = false;
		}
	}

	function selectTemplate(id: string | null) {
		selected = id;
		onSelect(id);
	}

	async function handleImport() {
		const input = document.createElement('input');
		input.type = 'file';
		input.accept = '.json';

		input.onchange = async () => {
			const file = input.files?.[0];
			if (!file) return;

			importing = true;
			errorMsg = null;

			try {
				const text = await file.text();
				const data = JSON.parse(text);

				const res = await fetch('/api/templates/import', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify(data)
				});

				const json = await res.json();
				if (json.success) {
					await loadTemplates();
					selectTemplate(json.data.id);
				} else {
					errorMsg = json.error ?? 'Failed to import template';
				}
			} catch {
				errorMsg = 'Failed to import template: invalid JSON file';
			} finally {
				importing = false;
			}
		};

		input.click();
	}

	// Load templates on mount
	$effect(() => {
		loadTemplates();
	});
</script>

<div class="space-y-3">
	<p class="text-sm font-medium text-foreground">Choose a template (optional)</p>

	{#if loading}
		<div class="flex items-center justify-center py-8 text-muted-foreground">
			<svg class="mr-2 h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
				<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" class="opacity-25" />
				<path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" class="opacity-75" />
			</svg>
			Loading templates...
		</div>
	{:else}
		<div class="grid grid-cols-2 gap-3 sm:grid-cols-3">
			<!-- Blank Board -->
			<button
				type="button"
				onclick={() => selectTemplate(null)}
				class="flex flex-col items-center gap-2 rounded-lg border-2 p-4 text-center transition-colors {selected === null ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/50'}"
			>
				<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
					<svg class="h-5 w-5 text-muted-foreground" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<line x1="12" y1="5" x2="12" y2="19" />
						<line x1="5" y1="12" x2="19" y2="12" />
					</svg>
				</div>
				<span class="text-sm font-medium text-foreground">Blank Board</span>
				<span class="text-xs text-muted-foreground">Start from scratch</span>
			</button>

			<!-- Templates -->
			{#each templates as template (template.id)}
				<button
					type="button"
					onclick={() => selectTemplate(template.id)}
					class="flex flex-col items-center gap-2 rounded-lg border-2 p-4 text-center transition-colors {selected === template.id ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/50'}"
				>
					<div class="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10">
						{#if template.icon}
							<DynamicIcon name={template.icon} size={20} />
						{:else}
							<svg class="h-5 w-5 text-primary" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
								<line x1="3" y1="9" x2="21" y2="9" />
								<line x1="9" y1="21" x2="9" y2="9" />
							</svg>
						{/if}
					</div>
					<span class="text-sm font-medium text-foreground">{template.name}</span>
					{#if template.description}
						<span class="line-clamp-2 text-xs text-muted-foreground">{template.description}</span>
					{/if}
					{#if template.config.sections.length > 0}
						<div class="flex flex-wrap justify-center gap-1">
							{#each template.config.sections as section (section.title)}
								<span class="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
									{section.title}
								</span>
							{/each}
						</div>
					{/if}
				</button>
			{/each}
		</div>

		<!-- Import button -->
		<div class="flex justify-end">
			<button
				type="button"
				onclick={handleImport}
				disabled={importing}
				class="text-xs text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"
			>
				{importing ? 'Importing...' : 'Import template from file'}
			</button>
		</div>
	{/if}

	{#if errorMsg}
		<div class="rounded-lg bg-destructive/10 p-2 text-xs text-destructive">
			{errorMsg}
		</div>
	{/if}
</div>
