<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Plus } from 'lucide-svelte';

	// Importar componentes de la librería
	import DataTable from '$lib/components/dashboard/transportation/transporters/data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/transportation/transporters/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/transportation/transporters/transporter-columns';

	import { transportersApi, type Transporter } from '$lib/api/dashboard/a76/transporters';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';

	// --- ESTADO ---
	let data = $state<Transporter[]>([]);
	let totalItems = $state(0);
	let pageCount = $state(0);
	let loading = $state(false);
	let createDialogOpen = $state(false);

	let currentPage = $derived(Number($page.url.searchParams.get('page')) || 1);
	let pageSize = 10;

	// Filtros
	let searchKey = $state($page.url.searchParams.get('transporter_key') || '');
	let searchName = $state($page.url.searchParams.get('name') || '');
	let searchTimeout: NodeJS.Timeout;

	// --- LOGICA ---
	async function loadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await transportersApi.list(companyStore.activeCompany.id, {
				page: currentPage,
				page_size: pageSize,
				transporter_key: searchKey,
				name: searchName
			});

			if (response.data) {
				data = response.data.items;
				totalItems = response.data.total;
				pageCount = Math.ceil(response.data.total / response.data.page_size);
			}
		} catch (error) {
			console.error('Error loading transporters:', error);
		} finally {
			loading = false;
		}
	}

	function handleSearch() {
		if (!browser) return;
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			const url = new URL($page.url);
			url.searchParams.set('page', '1');

			if (searchKey) url.searchParams.set('transporter_key', searchKey);
			else url.searchParams.delete('transporter_key');

			if (searchName) url.searchParams.set('name', searchName);
			else url.searchParams.delete('name');

			goto(url, { keepFocus: true, noScroll: true });
		}, 500);
	}

	// Recargar datos cuando cambia el contexto de compañía o la página/filtros
	$effect(() => {
		const _ = { p: $page.url.href, c: companyStore.activeCompany?.id };
		loadData();
	});

	const columns = createColumns(loadData);
</script>

<div class="flex h-full flex-col space-y-6 p-8">
	<div class="flex items-center justify-between">
		<div>
			<h2 class="text-2xl font-bold tracking-tight">Transportistas</h2>
			<p class="text-muted-foreground">Gestión del catálogo de líneas transportistas</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" /> Nuevo Transportista
		</Button>
	</div>

	<div class="flex items-center space-x-2">
		<Input
			placeholder="Buscar por clave..."
			class="h-8 w-[250px] bg-card"
			bind:value={searchKey}
			oninput={handleSearch}
		/>
		<Input
			placeholder="Buscar por nombre..."
			class="h-8 w-[250px] bg-card"
			bind:value={searchName}
			oninput={handleSearch}
		/>
	</div>

	{#if loading && data.length === 0}
		<div class="flex h-64 items-center justify-center text-muted-foreground">
			Cargando transportistas...
		</div>
	{:else}
		<DataTable {data} {columns} {pageCount} {totalItems} />
	{/if}

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