<script lang="ts">
	import { page } from '$app/stores';
	import DataTable from '$lib/components/dashboard/packages/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/packages/columns';
	import CreateEditDialog from '$lib/components/dashboard/packages/create-edit-dialog.svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Plus } from 'lucide-svelte';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import * as m from '$lib/paraglide/messages.js';

	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaBultos } from '$lib/config/shortcuts/dashboard/general_catalogs/packages/list';

	let { data } = $props();

	let createDialogOpen = $state(false);

	// Filtros
	let searchCode = $state($page.url.searchParams.get('code') || '');
	let searchName = $state($page.url.searchParams.get('name') || '');
	let timeout: ReturnType<typeof setTimeout>;

	// Atajos
	useShortcuts(
		'Lista Bultos',
		obtenerAtajosListaBultos({
			manejarNuevo: () => (createDialogOpen = true),
			manejarActualizar: handleSuccess,
		})
	);

	function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(() => {
			const url = new URL($page.url);

			if (searchCode) url.searchParams.set('code', searchCode);
			else url.searchParams.delete('code');

			if (searchName) url.searchParams.set('name', searchName);
			else url.searchParams.delete('name');

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

	function handleSuccess() {
		// Recargar datos
		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">Bultos y Embalajes</h1>
			<p class="text-muted-foreground">Gestión del catálogo de bultos y embalajes</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Bulto
		</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 clave..." bind:value={searchCode} oninput={handleSearch} />
		</div>
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input
				placeholder="Buscar por descripción..."
				bind:value={searchName}
				oninput={handleSearch}
			/>
		</div>
	</div>

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

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