<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/trailers/data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/transportation/trailers/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/transportation/trailers/columns';

	import { trailersApi, type Trailer } from '$lib/api/dashboard/a76/trailers';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';

	// --- ESTADO ---
	let data = $state<Trailer[]>([]);
	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 searchNumber = $state($page.url.searchParams.get('trailer_number') || '');
	let searchPlate = $state($page.url.searchParams.get('plate_number') || '');
	let searchTimeout: NodeJS.Timeout;

	// --- LOGICA ---
	async function loadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await trailersApi.list(companyStore.activeCompany.id, {
				page: currentPage,
				page_size: pageSize,
				trailer_number: searchNumber,
				plate_number: searchPlate
			});

			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 trailers:', 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 (searchNumber) url.searchParams.set('trailer_number', searchNumber);
			else url.searchParams.delete('trailer_number');

			if (searchPlate) url.searchParams.set('plate_number', searchPlate);
			else url.searchParams.delete('plate_number');

			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">Trailers</h2>
			<p class="text-muted-foreground">Gestión del catálogo de trailers de la compañía</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" /> Nuevo Trailer
		</Button>
	</div>

	<div class="flex items-center space-x-2">
		<Input
			placeholder="Buscar por número..."
			class="h-8 w-[250px] bg-card"
			bind:value={searchNumber}
			oninput={handleSearch}
		/>
		<Input
			placeholder="Buscar por placas..."
			class="h-8 w-[250px] bg-card"
			bind:value={searchPlate}
			oninput={handleSearch}
		/>
	</div>

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

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