<script lang="ts">
	import { page } from '$app/stores';
	import DataTable from '$lib/components/dashboard/general_catalogs/customs_broker_concepts/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/customs_broker_concepts/columns';
	import CreateEditDialog from '$lib/components/dashboard/general_catalogs/customs_broker_concepts/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 { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaConceptosAA } from '$lib/config/shortcuts/dashboard/general_catalogs/customs_broker_concepts/list';
	import { companyStore } from '$lib/stores/company.svelte';

	let { data } = $props();
	
	const activeCompanyId = $derived(companyStore.activeCompany?.id);
	let dialogOpen = $state(false);

	// Atajos
	useShortcuts(
		'Lista Conceptos AA',
		obtenerAtajosListaConceptosAA({
			manejarNuevo: () => (dialogOpen = true),
			manejarActualizar: () => goto($page.url, { invalidateAll: true }),
		})
	);

	// Filtros
	let searchBrokerKey = $state($page.url.searchParams.get('broker_key') || '');
	let searchConcept = $state($page.url.searchParams.get('concept') || '');
	let timeout: ReturnType<typeof setTimeout>;

	// Solo necesitamos una declaración de handleSuccess
	function handleSuccess() {
		const url = new URL($page.url);
		goto(url, { invalidateAll: true });
	}

	// columns depende de handleSuccess, así que se queda igual
	const columns = $derived(createColumns(handleSuccess));

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

			if (searchConcept) url.searchParams.set('concept', searchConcept);
			else url.searchParams.delete('concept');

			url.searchParams.set('page', '1');
			goto(url, { keepFocus: true, noScroll: true });
		}, 500);
	}
</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">Conceptos de Agente Aduanal</h1>
			<p class="text-muted-foreground">Gestión del catálogo de conceptos de agente aduanal</p>
		</div>
		<Button onclick={() => (dialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Concepto
		</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 de agente..."
				bind:value={searchBrokerKey}
				oninput={handleSearch}
			/>
		</div>
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input
				placeholder="Buscar por concepto..."
				bind:value={searchConcept}
				oninput={handleSearch}
			/>
		</div>
	</div>

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

	{#if activeCompanyId}
		<CreateEditDialog
			bind:open={dialogOpen}
			companyId={activeCompanyId}
			onSuccess={handleSuccess}
		/>
	{/if}
</div>
