<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import * as Table from '$lib/components/ui/table';
	import { Input } from '$lib/components/ui/input';
	import { Button } from '$lib/components/ui/button';
	import { Search, Loader2, Info, Package, AlertCircle } from 'lucide-svelte';
	import { companyStore } from '$lib/stores/company.svelte';

	let partsLoadError = $state('');

	let {
		open = $bindable(false),
		onSelect
	}: {
		open?: boolean;
		onSelect?: (part: any) => void;
	} = $props();

	let searchQuery = $state('');
	let debouncedSearch = $state('');
	let isSearching = $state(false);
	let isLoadingMore = $state(false);
	let parts = $state<any[]>([]);
	let currentPage = $state(1);
	let hasMore = $state(true);
	let totalItems = $state(0);
	const itemsPerPage = 25;

	async function fetchParts(page: number = 1, search: string = '') {
		const activeCompanyId = companyStore?.activeCompany?.id;
		if (!activeCompanyId) return;

		if (page === 1) isSearching = true;
		else isLoadingMore = true;

		try {
			const params = new URLSearchParams({
				company_id: activeCompanyId.toString(),
				page: page.toString(),
				page_size: itemsPerPage.toString(),
				sort_by: 'part_number',
				sort_order: 'asc'
			});

			if (search) {
				params.append('q', search);
			}

			const response = await fetch(`/api-sveltekit/parts?${params.toString()}`);
			if (!response.ok) throw new Error('Error al buscar números de parte');

			const data = await response.json();
			const newItems = data.items || [];

			if (page === 1) {
				parts = newItems;
			} else {
				parts = [...parts, ...newItems];
			}

			totalItems = data.total || 0;
			hasMore = newItems.length === itemsPerPage;
			currentPage = page;
		} catch (error) {
			console.error('Error fetching parts:', error);
			partsLoadError = 'No se pudieron cargar los números de parte. Intenta de nuevo.';
		} finally {
			isSearching = false;
			isLoadingMore = false;
		}
	}

	// Debounce effect
	$effect(() => {
		// Accedemos a searchQuery para que el efecto dependa de él
		const query = searchQuery;
		
		const timeout = setTimeout(() => {
			if (debouncedSearch !== query) {
				debouncedSearch = query;
				currentPage = 1;
				fetchParts(1, query);
			}
		}, 400);
		
		return () => clearTimeout(timeout);
	});

	function handleSelect(part: any) {
		if (onSelect) onSelect(part);
		open = false;
	}

	// Intersection Observer for Infinite Scroll
	let observerNode: HTMLElement | null = $state(null);
	
	$effect(() => {
		if (!observerNode || !hasMore || isSearching || isLoadingMore) return;

		const observer = new IntersectionObserver((entries) => {
			if (entries[0].isIntersecting) {
				fetchParts(currentPage + 1, debouncedSearch);
			}
		}, { threshold: 0.1 });

		observer.observe(observerNode);
		return () => observer.disconnect();
	});

	// Reset state when opening
	$effect(() => {
		if (open) {
			currentPage = 1;
			searchQuery = '';
			debouncedSearch = '';
			fetchParts(1, '');
		}
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-6xl max-h-[85vh] flex flex-col p-0 overflow-hidden bg-slate-50 dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
		<Dialog.Header class="p-6 pb-2">
			<div class="flex items-center gap-2 mb-1">
				<div class="p-1.5 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
					<Package class="w-5 h-5 text-blue-600 dark:text-blue-400" />
				</div>
				<Dialog.Title class="text-xl font-bold tracking-tight">Números de Parte</Dialog.Title>
			</div>
			<Dialog.Description class="text-sm text-muted-foreground ml-9">
				Busca y selecciona un número de parte del inventario maestro.
			</Dialog.Description>
		</Dialog.Header>

		<div class="px-6 py-2">
			<div class="relative group">
				<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-zinc-400 transition-colors group-focus-within:text-blue-500" />
				<Input
					placeholder="Buscar por código o descripción..."
					bind:value={searchQuery}
					class="pl-10 h-11 bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 shadow-sm focus:ring-2 focus:ring-blue-500/20 transition-all"
				/>
				{#if isSearching}
					<div class="absolute right-3 top-1/2 -translate-y-1/2">
						<Loader2 class="w-4 h-4 animate-spin text-blue-500" />
					</div>
				{/if}
			</div>
		</div>

		<div class="flex-1 overflow-y-auto px-6 py-2">
			<div class="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-xl overflow-hidden shadow-sm">
				<Table.Root>
					<Table.Header class="bg-zinc-50 dark:bg-zinc-800/50">
						<Table.Row class="hover:bg-transparent border-b border-zinc-200 dark:border-zinc-800">
							<Table.Head class="w-[180px] text-[10px] uppercase font-bold tracking-wider text-zinc-500 py-3">Número de Parte</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold tracking-wider text-zinc-500 py-3">Descripción (ES)</Table.Head>
							<Table.Head class="text-[10px] uppercase font-bold tracking-wider text-zinc-500 py-3">Descripción (EN)</Table.Head>
							<Table.Head class="w-[120px] text-[10px] uppercase font-bold tracking-wider text-zinc-500 py-3">Clase</Table.Head>
							<Table.Head class="w-[100px] py-3"></Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#each parts as part (part.id)}
							<Table.Row
								class="group cursor-pointer border-zinc-100 dark:border-zinc-800/50 hover:bg-blue-50/50 dark:hover:bg-blue-900/10 transition-colors"
								onclick={() => handleSelect(part)}
							>
								<Table.Cell class="font-mono text-xs font-semibold text-blue-600 dark:text-blue-400 py-3">
									{part.part_number}
								</Table.Cell>
								<Table.Cell class="text-sm py-3">
									<div class="line-clamp-2" title={part.description_spanish}>
										{part.description_spanish || '-'}
									</div>
								</Table.Cell>
								<Table.Cell class="text-sm py-3 text-zinc-500 italic">
									<div class="line-clamp-2" title={part.description_english}>
										{part.description_english || '-'}
									</div>
								</Table.Cell>
								<Table.Cell class="text-xs font-medium py-3">
									<span class="inline-flex items-center px-2 py-0.5 rounded-full bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 border border-zinc-200 dark:border-zinc-700">
										{part.part_class || '-'}
									</span>
								</Table.Cell>
								<Table.Cell class="text-right py-3 pr-4">
									<div class="opacity-0 group-hover:opacity-100 transition-opacity">
										<Button size="sm" variant="outline" class="h-7 text-[10px] font-bold uppercase bg-white dark:bg-zinc-800 hover:bg-blue-600 hover:text-white transition-all shadow-none border-zinc-200 dark:border-zinc-700" onclick={(e) => { e.stopPropagation(); handleSelect(part); }}>
											Seleccionar
										</Button>
									</div>
								</Table.Cell>
							</Table.Row>
						{:else}
							{#if !isSearching}
								<Table.Row>
									<Table.Cell colspan={5} class="h-[300px] text-center">
										<div class="flex flex-col items-center justify-center text-zinc-400 gap-2">
											<div class="p-3 bg-zinc-100 dark:bg-zinc-800 rounded-full">
												<Search class="w-6 h-6" />
											</div>
											<p class="text-sm font-medium">No hay resultados para esta búsqueda</p>
											<p class="text-xs">Verifica el número de parte o la descripción</p>
										</div>
									</Table.Cell>
								</Table.Row>
							{/if}
						{/each}

						<!-- Infinite Scroll Trigger -->
						{#if hasMore}
							<Table.Row class="border-none hover:bg-transparent">
								<Table.Cell colspan={5} class="p-0">
									<div bind:this={observerNode} class="h-20 flex items-center justify-center">
										{#if isLoadingMore}
											<div class="flex items-center gap-2 text-xs text-muted-foreground animate-pulse">
												<Loader2 class="w-4 h-4 animate-spin text-blue-500" />
												Cargando más números de parte...
											</div>
										{/if}
									</div>
								</Table.Cell>
							</Table.Row>
						{/if}
					</Table.Body>
				</Table.Root>
			</div>
		</div>

		<Dialog.Footer class="p-4 bg-white dark:bg-zinc-950 border-t border-zinc-200 dark:border-zinc-800 flex items-center justify-between sm:justify-between px-6">
			<div class="flex items-center gap-2 text-[10px] text-muted-foreground font-medium uppercase tracking-wider">
				<Info class="w-3 h-3 text-blue-500" />
				Mostrando {parts.length} de {totalItems} registros
			</div>
			<div class="flex gap-2">
				<Button variant="ghost" class="h-8 text-xs font-semibold hover:bg-zinc-100 dark:hover:bg-zinc-800" onclick={() => (open = false)}>
					Cerrar
				</Button>
			</div>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
