<script lang="ts">
	import { page } from '$app/stores';
	import DataTable from '$lib/components/dashboard/general_catalogs/company/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/company/columns';
	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 * as m from '$lib/paraglide/messages.js';

	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaEmpresa } from '$lib/config/shortcuts/dashboard/general_catalogs/company_information/list';

	let { data } = $props();

	// Atajos
	useShortcuts(
		'Lista Empresas',
		obtenerAtajosListaEmpresa({
			manejarNuevo: () => goto('/dashboard/general_catalogs/company_information/edit'),
			manejarActualizar: () => goto($page.url, { invalidateAll: true })
		})
	);
	let dialogOpen = $state(false);

	// Filtros
	let searchName = $state($page.url.searchParams.get('name') || '');
	let searchRfc = $state($page.url.searchParams.get('rfc') || '');
	let timeout: ReturnType<typeof setTimeout>;

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

			if (searchRfc) url.searchParams.set('rfc', searchRfc);
			else url.searchParams.delete('rfc');

			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">Información de Empresas</h1>
			<p class="text-muted-foreground">Gestión de información de empresas</p>
		</div>
		<Button href="/dashboard/general_catalogs/company_information/edit">
			<Plus class="mr-2 h-4 w-4" />
			Nueva Empresa
		</Button>
	</div>

	<div class="flex items-end gap-4">
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input placeholder="Buscar por nombre..." bind:value={searchName} oninput={handleSearch} />
		</div>
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input placeholder="Buscar por RFC..." bind:value={searchRfc} oninput={handleSearch} />
		</div>
	</div>

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