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

	let { data }: { data: PageData } = $props();

	let createDialogOpen = $state(false);

	// Atajos
	useShortcuts(
		'Lista Puertos',
		obtenerAtajosListaPuertos({
			manejarNuevo: () => (createDialogOpen = true),
			manejarActualizar: () => goto($page.url, { invalidateAll: true }),
		})
	);

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

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

			if (searchDesc) url.searchParams.set('description', searchDesc);
			else url.searchParams.delete('description');

			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">Puertos</h1>
			<p class="text-muted-foreground">Catálogo de puertos</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Puerto
		</Button>
	</div>

	{#if data.items?.error}
		<div
			class="rounded-md border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive"
		>
			{data.items.error}
		</div>
	{/if}

	<div class="flex gap-4 items-end">
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input placeholder="Buscar por código..." 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={searchDesc}
				oninput={handleSearch}
			/>
		</div>
	</div>

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

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