<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import type { Equivalency } from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
	import { createCatalogColumns } from '$lib/components/dashboard/general_catalogs/equivalencies/catalog-columns';
	import DataTable from '$lib/components/dashboard/general_catalogs/equivalencies/data-table.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 { obtenerAtajosListaEquivalencias } from '$lib/config/shortcuts/dashboard/general_catalogs/equivalencies/list';
	import DataEquivalenciesDialog from '$lib/components/dashboard/general_catalogs/equivalencies/data-equivalencies-dialog.svelte';
	import type { PageData } from './$types';

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

	let dataDialogOpen = $state(false);
	let selectedEquivalency = $state<Equivalency | null>(null);
	let dataMode = $state<'create' | 'edit'>('edit');

	// Atajos
	useShortcuts(
		'Lista Equivalencias',
		obtenerAtajosListaEquivalencias({
			manejarNuevo: () => {
				selectedEquivalency = null;
				dataMode = 'create';
				dataDialogOpen = true;
			},
			manejarActualizar: handleSuccess
		})
	);

	// Filtros
	let searchFrom = $state($page.url.searchParams.get('from_unit_code') || '');
	let timeout: ReturnType<typeof setTimeout>;

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

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

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

	function handleOpenInsertItems(equivalency: Equivalency) {
		selectedEquivalency = equivalency;
		dataMode = 'edit';
		dataDialogOpen = true;
	}

	function handleOpenEditCatalog(equivalency: Equivalency) {
		selectedEquivalency = equivalency;
		dataMode = 'edit';
		dataDialogOpen = 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">Equivalencias</h1>
			<p class="text-muted-foreground">Catálogo de equivalencias</p>
		</div>
		<Button
			onclick={() => {
				selectedEquivalency = null;
				dataMode = 'create';
				dataDialogOpen = true;
			}}
		>
			<Plus class="mr-2 h-4 w-4" />
			Nueva Equivalencia
		</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 código origen..."
				bind:value={searchFrom}
				oninput={handleSearch}
			/>
		</div>
	</div>

	<DataTable
		data={data.equivalencies.items}
		columns={createCatalogColumns({
			onInsertItems: handleOpenInsertItems,
			onEdit: handleOpenEditCatalog,
			onSuccess: handleSuccess
		})}
		pageCount={data.equivalencies.pages}
		totalItems={data.equivalencies.total}
	/>

	<DataEquivalenciesDialog
		bind:open={dataDialogOpen}
		equivalency={selectedEquivalency}
		mode={dataMode}
		onSuccess={handleSuccess}
	/>
</div>
