<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { fetchKetten, type KetteKurz, type Paginated } from '$lib/api';
	import { formatDate } from '$lib/status';
	import StatusBadge from '$lib/components/StatusBadge.svelte';

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

	// Filters from URL
	let filterStatus = $state('');
	let filterTyp = $state('');
	let filterSuche = $state('');
	let currentPage = $state(1);

	function syncFromUrl() {
		const p = new URL(window.location.href).searchParams;
		filterStatus = p.get('status') || '';
		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: '30' };
			if (filterStatus) params.status = filterStatus;
			if (filterTyp) params.typ = filterTyp;
			if (filterSuche) params.suche = filterSuche;
			data = await fetchKetten(params);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Fehler';
		} finally {
			loading = false;
		}
	}

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

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

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

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

<div class="mb-6">
	<h1 class="text-2xl font-bold text-gray-900">Ketten</h1>
	<p class="text-gray-500 text-sm mt-1">Zusammengehörige Vorlagen als Ketten nachverfolgen</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="Thema suchen..."
				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="status" class="block text-xs font-medium text-gray-500 mb-1">Status</label>
			<select id="status" bind:value={filterStatus} 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="eingereicht">Eingereicht</option>
				<option value="in_beratung">In Beratung</option>
				<option value="vertagt">Vertagt</option>
				<option value="beschlossen">Beschlossen</option>
				<option value="umgesetzt">Umgesetzt</option>
				<option value="abgelehnt">Abgelehnt</option>
				<option value="versandet">Versandet</option>
				<option value="angefragt">Angefragt</option>
				<option value="beantwortet">Beantwortet</option>
				<option value="offen">Offen</option>
				<option value="abgewiegelt">Abgewiegelt</option>
			</select>
		</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>
			</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} Ketten 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">Thema</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">Status</th>
					<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Glieder</th>
					<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Letzte Akt.</th>
				</tr>
			</thead>
			<tbody class="divide-y divide-gray-100">
				{#each data.items as kette}
					<tr class="hover:bg-gray-50 transition-colors cursor-pointer" onclick={() => goto(`/ketten/${kette.id}`)}>
						<td class="px-4 py-3">
							<a href="/ketten/{kette.id}" class="font-mono text-sm font-medium text-green-700 hover:underline">
								{kette.ursprung?.aktenzeichen || `#${kette.id}`}
							</a>
						</td>
						<td class="px-4 py-3 text-sm text-gray-700 max-w-md truncate">{kette.thema || '-'}</td>
						<td class="px-4 py-3 text-sm text-gray-600 capitalize">{kette.typ || '-'}</td>
						<td class="px-4 py-3"><StatusBadge status={kette.status} /></td>
						<td class="px-4 py-3 text-sm text-gray-600">{kette.glieder_count}</td>
						<td class="px-4 py-3 text-sm text-gray-500">{formatDate(kette.letzte_aktivitaet)}</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}
