<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';

	import DataTable from '$lib/components/dashboard/transportation/drivers/data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/transportation/drivers/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/transportation/drivers/columns';

	import { driversApi, type Driver } from '$lib/api/dashboard/a76/drivers';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';

	let data = $state<Driver[]>([]);
	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;

	let searchTransporterKey = $state($page.url.searchParams.get('transporter_key') || '');
	let searchDriverName = $state($page.url.searchParams.get('driver_name') || '');
	let searchTimeout: NodeJS.Timeout;

	async function loadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const params: Record<string, string | number> = {
				page: currentPage,
				page_size: pageSize
			};
			// Filtros: el backend aún no los soporta; se mantienen en URL para futura implementación
			// if (searchTransporterKey) params.transporter_key = searchTransporterKey;
			// if (searchDriverName) params.driver_name = searchDriverName;

			const response = await driversApi.list(companyStore.activeCompany.id, params);

			if (response.data) {
				data = response.data.items;
				totalItems = response.data.total;
				pageCount = Math.ceil(response.data.total / response.data.page_size) || 1;
			}
		} catch (error) {
			console.error('Error loading drivers:', 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 (searchTransporterKey) url.searchParams.set('transporter_key', searchTransporterKey);
			else url.searchParams.delete('transporter_key');
			if (searchDriverName) url.searchParams.set('driver_name', searchDriverName);
			else url.searchParams.delete('driver_name');
			goto(url, { keepFocus: true, noScroll: true });
		}, 500);
	}

	$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">Conductores</h2>
			<p class="text-muted-foreground">Gestión del catálogo de conductores</p>
		</div>
		<Button onclick={() => (createDialogOpen = true)}>
			<Plus class="mr-2 h-4 w-4" /> Nuevo Conductor
		</Button>
	</div>

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

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

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