<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { fetchVorlagen, type VorlageKurz, type Paginated } from '$lib/api';
	import { formatDate } from '$lib/status';

	let data: Paginated<VorlageKurz> | null = $state(null);
	let error: string | null = $state(null);
	let loading = $state(false);

	let filterTyp = $state('');
	let filterSuche = $state('');
	let currentPage = $state(1);

	function syncFromUrl() {
		const p = new URL(window.location.href).searchParams;
		filterTyp = p.get('typ') || '';
		filterSuche = p.get('suche') || '';
		currentPage = parseInt(p.get('page') || '1');
	}

	async function load() {
		loading = true;
		try {
			const params: Record<string, string> = { page: String(currentPage), page_size: '50' };
			if (filterTyp) params.typ = filterTyp;
			if (filterSuche) params.suche = filterSuche;
			data = await fetchVorlagen(params);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Fehler';
		} finally {
			loading = false;
		}
	}

	function applyFilters() {
		const params = new URLSearchParams();
		if (filterTyp) params.set('typ', filterTyp);
		if (filterSuche) params.set('suche', filterSuche);
		currentPage = 1;
		params.set('page', '1');
		goto(`/vorlagen?${params.toString()}`, { replaceState: true });
		load();
	}

	function goPage(p: number) {
		currentPage = p;
		const params = new URLSearchParams(window.location.search);
		params.set('page', String(p));
		goto(`/vorlagen?${params.toString()}`, { replaceState: true });
		load();
	}

	onMount(() => {
		syncFromUrl();
		load();
	});
</script>

<svelte:head>
	<title>Vorlagen - Antragstracker Hagen</title>
</svelte:head>

<div class="mb-6">
	<h1 class="text-2xl font-bold text-gray-900">Vorlagen</h1>
	<p class="text-gray-500 text-sm mt-1">Alle importierten Vorlagen aus dem ALLRIS-System</p>
</div>

<!-- Filters -->
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
	<div class="flex flex-wrap gap-3 items-end">
		<div>
			<label for="suche" class="block text-xs font-medium text-gray-500 mb-1">Suche</label>
			<input id="suche" type="text" bind:value={filterSuche} placeholder="Betreff oder Aktenzeichen..."
				class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-green-500 focus:border-green-500"
				onkeydown={(e) => { if (e.key === 'Enter') applyFilters(); }} />
		</div>
		<div>
			<label for="typ" class="block text-xs font-medium text-gray-500 mb-1">Typ</label>
			<select id="typ" bind:value={filterTyp} onchange={applyFilters}
				class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-green-500">
				<option value="">Alle</option>
				<option value="antrag">Antrag</option>
				<option value="anfrage">Anfrage</option>
				<option value="stellungnahme">Stellungnahme</option>
				<option value="bericht">Bericht</option>
			</select>
		</div>
		<button onclick={applyFilters}
			class="bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-green-700 transition-colors">
			Filtern
		</button>
	</div>
</div>

{#if error}
	<div class="bg-red-50 text-red-700 p-4 rounded-lg">{error}</div>
{:else if loading && !data}
	<div class="flex justify-center py-20">
		<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
	</div>
{:else if data}
	<div class="text-sm text-gray-500 mb-3">{data.total} Vorlagen gefunden</div>

	<div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
		<table class="w-full">
			<thead class="bg-gray-50">
				<tr>
					<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aktenzeichen</th>
					<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Betreff</th>
					<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Typ</th>
					<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Datum</th>
				</tr>
			</thead>
			<tbody class="divide-y divide-gray-100">
				{#each data.items as v}
					<tr class="hover:bg-gray-50 transition-colors cursor-pointer" onclick={() => goto(`/vorlagen/${v.id}`)}>
						<td class="px-4 py-3">
							<a href="/vorlagen/{v.id}" class="font-mono text-sm font-medium text-green-700 hover:underline">
								{v.aktenzeichen || `#${v.id}`}
							</a>
						</td>
						<td class="px-4 py-3 text-sm text-gray-700 max-w-lg truncate">{v.betreff || '-'}</td>
						<td class="px-4 py-3 text-sm text-gray-600 capitalize">{v.typ || '-'}</td>
						<td class="px-4 py-3 text-sm text-gray-500">{formatDate(v.datum_eingang)}</td>
					</tr>
				{/each}
			</tbody>
		</table>
	</div>

	<!-- Pagination -->
	{#if data.total > data.page_size}
		{@const totalPages = Math.ceil(data.total / data.page_size)}
		<div class="flex justify-center mt-6 space-x-2">
			<button disabled={currentPage <= 1} onclick={() => goPage(currentPage - 1)}
				class="px-3 py-2 rounded-lg text-sm border border-gray-300 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
				&laquo; Zurück
			</button>
			<span class="px-3 py-2 text-sm text-gray-600">Seite {currentPage} von {totalPages}</span>
			<button disabled={currentPage >= totalPages} onclick={() => goPage(currentPage + 1)}
				class="px-3 py-2 rounded-lg text-sm border border-gray-300 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
				Weiter &raquo;
			</button>
		</div>
	{/if}
{/if}
