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

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

	let createDialogOpen = $state(false);

	// Atajos
	useShortcuts(
		'Lista Tipos de Cambio',
		obtenerAtajosListaTiposCambio({
			manejarNuevo: () => (createDialogOpen = true),
			manejarActualizar: handleSuccess
		})
	);

	// Filtros
	// Exchange rate usually has date filter, but for consistency with others I'll check what columns it has.
	// It has date, value, local_currency.
	// I'll add a date filter if possible, or just leave it without filters if not applicable easily,
	// but the pattern requires filters. Maybe filter by local_currency?
	// Let's check the columns again.
	// columns.ts has: date, value, local_currency.

	let searchCurrency = $state($page.url.searchParams.get('local_currency') || '');
	let timeout: ReturnType<typeof setTimeout>;

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

			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">Tipos de Cambio</h1>
			<p class="text-muted-foreground">Catálogo de tipos de cambio</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Tipo de Cambio
		</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 moneda..."
				bind:value={searchCurrency}
				oninput={handleSearch}
			/>
		</div>
	</div>

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

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