<script lang="ts">
	import { onMount } from 'svelte';

	interface ImportTask {
		id: string;
		slug: string;
		title: string;
		file_name: string;
		file_type: string;
		status: string;
		chapters_done: number;
		chapters_total: number;
		error_message: string;
		started: string;
		finished: string;
	}

	interface PendingImport {
		file: File;
		title: string;
		preview: { chapters: number; firstLines: string[] };
	}

	let tasks = $state<ImportTask[]>([]);
	let loading = $state(true);
	let uploading = $state(false);
	let title = $state('');
	let error = $state('');
	let selectedFile = $state<File | null>(null);
	let pendingImport = $state<PendingImport | null>(null);
	let analyzing = $state(false);

	async function loadTasks() {
		loading = true;
		try {
			const res = await fetch('/api/admin/import');
			if (res.ok) {
				const data = await res.json();
				tasks = data.tasks || [];
			}
		} catch (e) {
			console.error('Failed to load tasks:', e);
		} finally {
			loading = false;
		}
	}

	async function handleFileSelect(e: Event) {
		const input = e.target as HTMLInputElement;
		if (!input.files?.length) return;
		const file = input.files[0];
		const ext = file.name.split('.').pop()?.toLowerCase() || '';
		if (ext !== 'pdf' && ext !== 'epub') {
			error = 'Please select a PDF or EPUB file';
			return;
		}
		selectedFile = file;
		title = file.name.replace(/\.(pdf|epub)$/i, '').replace(/[-_]/g, ' ');
	}

	async function analyzeFile() {
		if (!selectedFile || !title.trim()) return;
		analyzing = true;
		error = '';
		try {
			const formData = new FormData();
			formData.append('file', selectedFile);
			formData.append('title', title);
			formData.append('analyze', 'true');
			const res = await fetch('/api/admin/import', {
				method: 'POST',
				body: formData
			});
			if (res.ok) {
				const data = await res.json();
				pendingImport = {
					file: selectedFile,
					title: title,
					preview: data.preview || { chapters: 0, firstLines: [] }
				};
			} else {
				const d = await res.json().catch(() => ({}));
				error = d.error || 'Failed to analyze file';
			}
		} catch (e) {
			error = 'Failed to analyze file';
		} finally {
			analyzing = false;
		}
	}

	async function startImport() {
		if (!pendingImport) return;
		uploading = true;
		error = '';
		try {
			const formData = new FormData();
			formData.append('file', pendingImport.file);
			formData.append('title', pendingImport.title);
			const res = await fetch('/api/admin/import', {
				method: 'POST',
				body: formData
			});
			if (res.ok) {
				pendingImport = null;
				selectedFile = null;
				title = '';
				await loadTasks();
			} else {
				const d = await res.json().catch(() => ({}));
				error = d.error || 'Import failed';
			}
		} catch (e) {
			error = 'Import failed';
		} finally {
			uploading = false;
		}
	}

	function cancelReview() {
		pendingImport = null;
	}

	function formatDate(dateStr: string) {
		if (!dateStr) return '-';
		return new Date(dateStr).toLocaleString();
	}

	function getStatusColor(status: string) {
		switch (status) {
			case 'pending': return 'text-yellow-400';
			case 'running': return 'text-blue-400';
			case 'done': return 'text-green-400';
			case 'failed': return 'text-red-400';
			default: return 'text-gray-400';
		}
	}

	onMount(() => {
		loadTasks();
	});

	// Poll every 3s while any task is running
	$effect(() => {
		const hasRunning = tasks.some((t) => t.status === 'running' || t.status === 'pending');
		if (!hasRunning) return;
		const timer = setInterval(() => {
			loadTasks();
		}, 3000);
		return () => clearInterval(timer);
	});
</script>

<div class="max-w-4xl">
	<h1 class="text-2xl font-bold mb-6">Import PDF/EPUB</h1>

	{#if pendingImport}
		<!-- Review Step -->
		<div class="mb-8 p-6 bg-(--color-surface-2) rounded-lg border border-(--color-brand)/30">
			<h2 class="text-lg font-semibold mb-4">Review Import</h2>
			<div class="space-y-3 mb-6">
				<div class="flex justify-between">
					<span class="text-(--color-muted)">Title:</span>
					<span class="font-medium">{pendingImport.title}</span>
				</div>
				<div class="flex justify-between">
					<span class="text-(--color-muted)">File:</span>
					<span>{pendingImport.file.name}</span>
				</div>
				<div class="flex justify-between">
					<span class="text-(--color-muted)">Size:</span>
					<span>{(pendingImport.file.size / 1024 / 1024).toFixed(2)} MB</span>
				</div>
				{#if pendingImport.preview.chapters > 0}
					<div class="flex justify-between">
						<span class="text-(--color-muted)">Detected chapters:</span>
						<span class="text-green-400">{pendingImport.preview.chapters}</span>
					</div>
				{/if}
			</div>
			<div class="flex gap-3">
				<button
					onclick={startImport}
					disabled={uploading}
					class="px-4 py-2 bg-green-600 text-white rounded font-medium disabled:opacity-50"
				>
					{uploading ? 'Starting...' : 'Start Import'}
				</button>
				<button
					onclick={cancelReview}
					class="px-4 py-2 border border-(--color-border) rounded font-medium"
				>
					Cancel
				</button>
			</div>
		</div>
	{:else}
		<!-- Upload Form -->
		<form onsubmit={(e) => { e.preventDefault(); analyzeFile(); }} class="mb-8 p-4 bg-(--color-surface-2) rounded-lg">
			<div class="mb-4">
				<label for="import-file" class="block text-sm font-medium mb-2">Select File (PDF or EPUB)</label>
				<input
					id="import-file"
					type="file"
					accept=".pdf,.epub"
					onchange={handleFileSelect}
					class="w-full px-3 py-2 rounded bg-(--color-surface) border border-(--color-border) text-(--color-text)"
				/>
			</div>
			<div class="mb-4">
				<label for="import-title" class="block text-sm font-medium mb-2">Book Title</label>
				<input
					id="import-title"
					type="text"
					bind:value={title}
					placeholder="Enter book title"
					class="w-full px-3 py-2 rounded bg-(--color-surface) border border-(--color-border) text-(--color-text)"
				/>
			</div>
			{#if error}
				<p class="mb-4 text-sm text-red-400">{error}</p>
			{/if}
			<button
				type="submit"
				disabled={analyzing || !selectedFile || !title.trim()}
				class="px-4 py-2 bg-(--color-brand) text-(--color-surface) rounded font-medium disabled:opacity-50"
			>
				{analyzing ? 'Analyzing...' : 'Review & Import'}
			</button>
			<p class="mt-2 text-xs text-(--color-muted)">
				Select a file to preview chapter count before importing.
			</p>
		</form>
	{/if}

	<!-- Task List -->
	<h2 class="text-lg font-semibold mb-4">Import Tasks</h2>

	{#if loading}
		<p class="text-(--color-muted)">Loading...</p>
	{:else if tasks.length === 0}
		<p class="text-(--color-muted)">No import tasks yet.</p>
	{:else}
		<div class="overflow-x-auto">
			<table class="w-full text-sm">
				<thead>
					<tr class="text-left text-(--color-muted) border-b border-(--color-border)">
						<th class="pb-2">Title</th>
						<th class="pb-2">Type</th>
						<th class="pb-2">Status</th>
						<th class="pb-2">Chapters</th>
						<th class="pb-2">Started</th>
					</tr>
				</thead>
				<tbody>
					{#each tasks as task}
						<tr class="border-b border-(--color-border)/50">
							<td class="py-2">
								<div class="font-medium">{task.title}</div>
								<div class="text-xs text-(--color-muted)">{task.slug}</div>
							</td>
							<td class="py-2 uppercase text-xs">{task.file_type}</td>
							<td class="py-2 {getStatusColor(task.status)}">{task.status}</td>
							<td class="py-2 text-(--color-muted)">
								{task.chapters_done}/{task.chapters_total}
							</td>
							<td class="py-2 text-(--color-muted)">{formatDate(task.started)}</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	{/if}
</div>