<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, Tag, Ruler } from 'lucide-svelte';
	import { classesApi, type A76Class } from '$lib/api/dashboard/a76/classes';
	import { companyStore } from '$lib/stores/company.svelte';

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

	let items = $state<A76Class[]>([]);
	let total = $state(0);
	let currentPage = $state(1);
	let loading = $state(false);
	let loadingMore = $state(false);
	let searchTerm = $state('');

	const PAGE_SIZE = 100;

	const hasMore = $derived(items.length < total && total > 0);

	async function loadPage(trimmed: string, page: number, append: boolean) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		if (append) {
			if (loadingMore || loading || !hasMore) return;
		} else if (loading) {
			return;
		}

		if (page === 1) {
			loading = true;
		} else {
			loadingMore = true;
		}

		try {
			const res = await classesApi.list({
				company_id: companyId,
				page,
				page_size: PAGE_SIZE,
				...(trimmed ? { search: trimmed } : {})
			});

			const data = (res as { data?: { items?: A76Class[]; total?: number } }).data ?? res;
			const raw = (data as { items?: A76Class[] }).items ?? [];
			const newItems = Array.isArray(raw) ? raw : [];

			if (append && newItems.length === 0) {
				total = items.length;
				return;
			}

			const t =
				typeof (data as { total?: number }).total === 'number'
					? (data as { total: number }).total
					: append
						? items.length + newItems.length
						: newItems.length;

			if (append) {
				items = [...items, ...newItems];
			} else {
				items = newItems;
			}
			total = t;
			currentPage = page;
		} catch (e) {
			console.error('Error cargando clases:', e);
			if (!append) {
				items = [];
				total = 0;
			}
		} finally {
			loading = false;
			loadingMore = false;
		}
	}

	function handleScroll(e: Event) {
		const target = e.currentTarget as HTMLDivElement;
		const threshold = 80;
		if (target.scrollHeight - target.scrollTop - target.clientHeight > threshold) return;
		if (!hasMore || loading || loadingMore) return;
		const term = searchTerm.trim();
		loadPage(term, currentPage + 1, true);
	}

	$effect(() => {
		if (!open) {
			searchTerm = '';
			items = [];
			total = 0;
			currentPage = 1;
		}
	});

	$effect(() => {
		if (!open) return;
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		const term = searchTerm.trim();
		const delayMs = term === '' ? 0 : 300;
		const handle = setTimeout(() => {
			loadPage(term, 1, false);
		}, delayMs);
		return () => clearTimeout(handle);
	});

	function handleSelect(item: A76Class) {
		if (onSelect) onSelect(item);
		open = false;
	}
</script>

<Dialog.Root bind:open={open}>
	<Dialog.Content class="sm:max-w-[700px] max-h-[80vh] flex flex-col z-[300]">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Clase (Anexo 24)</Dialog.Title>
			<Dialog.Description>
				Seleccione la clasificación del material. Desplace hacia abajo para cargar más resultados.
			</Dialog.Description>
		</Dialog.Header>

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

		<div class="flex-1 flex flex-col overflow-hidden border rounded-md min-h-[300px]">
			<!-- Header fuera del contenedor scrollable para evitar desplazamiento en hit-testing -->
			<table class="w-full text-sm shrink-0">
				<thead class="bg-muted/50">
					<tr class="text-left border-b">
						<th class="p-3 font-medium text-muted-foreground w-[100px]">Clave</th>
						<th class="p-3 font-medium text-muted-foreground">Descripción</th>
						<th class="p-3 font-medium text-muted-foreground w-[80px]">UM</th>
					</tr>
				</thead>
			</table>
			<div class="flex-1 overflow-y-auto" onscroll={handleScroll}>
			{#if loading}
				<div class="flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground">
					<Loader2 class="h-8 w-8 animate-spin text-primary" />
					<p>Cargando catálogo...</p>
				</div>
			{:else if items.length === 0}
				<div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
					<p>No se encontraron clases.</p>
				</div>
			{:else}
				<table class="w-full text-sm">
					<tbody>
						{#each items as item}
							<tr
								class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
								onclick={() => handleSelect(item)}
							>
								<td class="p-3">
									<span
										class="font-mono font-bold text-primary bg-primary/10 px-2 py-1 rounded text-xs"
									>
										{item.class_code}
									</span>
								</td>

								<td class="p-3">
									<div class="flex items-center gap-2">
										<Tag class="h-3 w-3 text-muted-foreground shrink-0" />
										<span
											class="truncate max-w-[300px]"
											title={item.description_es || item.description_en || ''}
										>
											{item.description_es || item.description_en || 'Sin descripción'}
										</span>
									</div>
								</td>

								<td class="p-3">
									<div class="flex items-center gap-1 text-xs text-muted-foreground">
										<Ruler class="h-3 w-3" />
										{item.unit_of_measure || '-'}
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
				{#if loadingMore}
					<div class="flex justify-center py-3 text-muted-foreground">
						<Loader2 class="h-6 w-6 animate-spin" />
					</div>
				{/if}
			{/if}
			</div>
		</div>

		<Dialog.Footer>
			<div class="text-xs text-muted-foreground self-center mr-auto">
				{#if loading}
					…
				{:else}
					Mostrando {items.length} de {total} registros
				{/if}
			</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>
