<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/unit_conversions/columns';
	import CreateEditDialog from '$lib/components/dashboard/general_catalogs/unit_conversions/create-edit-dialog.svelte';
	import DataTable from '$lib/components/dashboard/general_catalogs/unit_conversions/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 { obtenerAtajosListaConversiones } from '$lib/config/shortcuts/dashboard/general_catalogs/unit_conversions/list';

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

	let createDialogOpen = $state(false);

	// Atajos
	useShortcuts(
		'Lista Conversiones',
		obtenerAtajosListaConversiones({
			manejarNuevo: () => (createDialogOpen = true),
			manejarRefrescar: handleSuccess
		})
	);

	// Filtros
	let searchFrom = $state($page.url.searchParams.get('from_unit_code') || '');
	let searchTo = $state($page.url.searchParams.get('to_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');

			if (searchTo) url.searchParams.set('to_unit_code', searchTo);
			else url.searchParams.delete('to_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 });
	}
</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">Conversiones de Unidades</h1>
			<p class="text-muted-foreground">Catálogo de conversiones de unidades de medida</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" />
			Nueva Conversión
		</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 desde código..." bind:value={searchFrom} oninput={handleSearch} />
		</div>
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input placeholder="Buscar hacia código..." bind:value={searchTo} oninput={handleSearch} />
		</div>
	</div>

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

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