<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import DataTable from '$lib/components/dashboard/general_catalogs/electronic_notices/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/electronic_notices/columns.js';
	import CreateEditDialog from '$lib/components/dashboard/general_catalogs/electronic_notices/create-edit-dialog.svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Plus } from 'lucide-svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaAvisosElectrónicos } from '$lib/config/shortcuts/dashboard/general_catalogs/electronic_notices/list';

	let { data } = $props();
	let dialogOpen = $state(false);

	// Atajos
	useShortcuts(
		'Lista Avisos Electrónicos',
		obtenerAtajosListaAvisosElectrónicos({
			manejarNuevo: () => (dialogOpen = true),
			manejarRefrescar: handleSuccess
		})
	);

	// Filtros
	let searchNotice = $state($page.url.searchParams.get('notice_number') || '');
	let searchPedimento = $state($page.url.searchParams.get('pedimento') || '');
	let timeout: ReturnType<typeof setTimeout>;

	function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(() => {
			const url = new URL($page.url);
			if (searchNotice) url.searchParams.set('notice_number', searchNotice);
			else url.searchParams.delete('notice_number');

			if (searchPedimento) url.searchParams.set('pedimento', searchPedimento);
			else url.searchParams.delete('pedimento');

			url.searchParams.set('page', '1');
			goto(url, { keepFocus: true, noScroll: true });
		}, 500);
	}

	function handleSuccess() {
		const url = new URL($page.url);
		goto(url, { invalidateAll: true });
	}
</script>

<div class="flex flex-col gap-4 p-4">
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Avisos Electrónicos</h1>
			<p class="text-muted-foreground">Gestión del catálogo de avisos electrónicos</p>
		</div>
		<Button onclick={() => (dialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Aviso
		</Button>
	</div>

	<div class="flex gap-4 items-end">
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input
				placeholder="Buscar por No. Aviso..."
				bind:value={searchNotice}
				oninput={handleSearch}
			/>
		</div>
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input
				placeholder="Buscar por Pedimento..."
				bind:value={searchPedimento}
				oninput={handleSearch}
			/>
		</div>
	</div>

	<div class="rounded-md border">
		<DataTable
			data={data.notices?.items || []}
			columns={createColumns(handleSuccess)}
			pageCount={data.notices?.pages || 0}
			totalItems={data.notices?.total || 0}
		/>
	</div>

	<CreateEditDialog bind:open={dialogOpen} onSuccess={handleSuccess} />
</div>
