<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Search, Loader2, Truck } from 'lucide-svelte';
	import { trailersApi, type Trailer } from '$lib/api/dashboard/a76/trailers';
	import { companyStore } from '$lib/stores/company.svelte';

	let {
		open = $bindable(false),
		onSelect,
		onClear
	}: {
		open: boolean;
		onSelect: (item: Trailer) => void;
		onClear?: () => void;
	} = $props();

	let items = $state<Trailer[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let loaded = $state(false);

	let filteredItems = $derived(
		items.filter(
			(i) =>
				i.trailer_number?.toLowerCase().includes(searchTerm.toLowerCase()) ||
				i.plate_number?.toLowerCase().includes(searchTerm.toLowerCase())
		)
	);

	$effect(() => {
		if (open && !loaded && companyStore.activeCompany?.id) {
			loadItems();
		}
	});

	async function loadItems() {
		if (!companyStore.activeCompany?.id) return;
		loading = true;
		try {
			const res = await trailersApi.list(companyStore.activeCompany.id);
			const data = (res as any).data || res;
			if (data && data.items) {
				items = data.items;
				loaded = true;
			}
		} catch (e) {
			console.error('Error loading trailers:', e);
		} finally {
			loading = false;
		}
	}

	function handleSelect(item: Trailer) {
		if (onSelect) onSelect(item);
		open = false;
	}

	function handleRowKeydown(event: KeyboardEvent, item: Trailer) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			handleSelect(item);
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="flex max-h-[80vh] flex-col sm:max-w-[600px]">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Trailer</Dialog.Title>
			<Dialog.Description>Busca y selecciona un trailer registrado.</Dialog.Description>
		</Dialog.Header>

		<div class="relative my-2 w-full">
			<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
			<Input
				type="search"
				placeholder="Buscar por número o placas..."
				class="pl-9"
				bind:value={searchTerm}
			/>
		</div>

		<div class="min-h-[300px] flex-1 overflow-y-auto rounded-md border">
			{#if loading}
				<div class="flex h-48 flex-col items-center justify-center gap-2 text-muted-foreground">
					<Loader2 class="h-8 w-8 animate-spin text-primary" />
					<p>Cargando catálogo...</p>
				</div>
			{:else if filteredItems.length === 0}
				<div class="flex h-48 flex-col items-center justify-center text-muted-foreground">
					<p>No se encontraron trailers.</p>
				</div>
			{:else}
				<table class="w-full text-sm">
					<thead class="bg-muted/50">
						<tr class="border-b text-left">
							<th class="p-3 font-medium text-muted-foreground">Número de Trailer</th>
							<th class="p-3 font-medium text-muted-foreground">Placas</th>
							<th class="w-[100px] p-3 text-center font-medium text-muted-foreground">Estado</th>
						</tr>
					</thead>
					<tbody>
						{#each filteredItems as item}
							<tr
								class="cursor-pointer border-b transition-colors hover:bg-accent/50"
								tabindex="0"
								onclick={() => handleSelect(item)}
								onkeydown={(event) => handleRowKeydown(event, item)}
							>
								<td class="p-3 font-mono font-bold text-blue-600">{item.trailer_number}</td>
								<td class="p-3 font-mono text-xs">{item.plate_number || '-'}</td>
								<td class="p-3 text-center">
									{#if item.is_active}
										<span
											class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-[10px] font-medium text-green-800"
										>
											Disponible
										</span>
									{:else}
										<span
											class="inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-[10px] font-medium text-red-800"
										>
											Inactivo
										</span>
									{/if}
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			{/if}
		</div>

		<Dialog.Footer>
			<div class="mr-auto self-center text-xs text-muted-foreground">
				Mostrando {filteredItems.length} registros
			</div>
			{#if onClear}
				<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
