<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 } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';

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

	let searchQuery = $state('');
	let isSearching = $state(false);
	let parts = $state<any[]>([]);
	let displayedParts = $state<any[]>([]);
	let currentPage = $state(1);
	let itemsPerPage = 10;

	const filteredParts = $derived(
		searchQuery
			? parts.filter(p => 
				p.part_number?.toLowerCase().includes(searchQuery.toLowerCase()) ||
				p.description_spanish?.toLowerCase().includes(searchQuery.toLowerCase()) ||
				p.description_english?.toLowerCase().includes(searchQuery.toLowerCase())
			)
			: parts
	);

	$effect(() => {
		if (open) {
			searchParts();
		}
	});

	$effect(() => {
		currentPage = 1;
		loadMoreParts();
	});

	async function searchParts() {
		const activeCompanyId = companyStore?.activeCompany?.id;
		if (!activeCompanyId) {
			toast.error('No hay compañía activa');
			return;
		}

		isSearching = true;
		try {
			const response = await fetch(
				`/api-sveltekit/parts?company_id=${activeCompanyId}&limit=100`,
				{
					method: 'GET',
					headers: {
						'Content-Type': 'application/json'
					}
				}
			);

			if (!response.ok) {
				throw new Error('Error al buscar números de parte');
			}

			const data = await response.json();
			parts = data.items || [];
			loadMoreParts();
		} catch (error) {
			console.error('Error searching parts:', error);
			toast.error('Error al buscar números de parte');
			parts = [];
		} finally {
			isSearching = false;
		}
	}

	function loadMoreParts() {
		const start = 0;
		const end = currentPage * itemsPerPage;
		displayedParts = filteredParts.slice(start, end);
	}

	function handleScroll(e: Event) {
		const target = e.target as HTMLDivElement;
		const threshold = 100;
		const scrolledToBottom = target.scrollHeight - target.scrollTop - target.clientHeight < threshold;
		
		if (scrolledToBottom && displayedParts.length < filteredParts.length) {
			currentPage++;
			loadMoreParts();
		}
	}

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

<Dialog.Root bind:open>
	<Dialog.Content class="!max-w-[50vw] w-[50vw] max-h-[80vh] flex flex-col">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Número de Parte</Dialog.Title>
			<Dialog.Description>
				Busca y selecciona un número de parte para la partida
			</Dialog.Description>
		</Dialog.Header>

		<div class="flex gap-2 mb-4">
			<div class="relative flex-1">
				<Search class="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
				<Input
					placeholder="Buscar por número de parte o descripción..."
					bind:value={searchQuery}
					class="pl-8"
				/>
			</div>
		</div>

		<div class="flex-1 overflow-auto border rounded-md" onscroll={handleScroll}>
			{#if isSearching}
				<div class="flex items-center justify-center py-8">
					<Loader2 class="w-6 h-6 animate-spin text-muted-foreground" />
				</div>
			{:else}
				<Table.Root>
					<Table.Header class="sticky top-0 bg-background z-10">
						<Table.Row>
							<Table.Head class="w-[150px]">Número de Parte</Table.Head>
							<Table.Head>Descripción (ES)</Table.Head>
							<Table.Head>Descripción (EN)</Table.Head>
							<Table.Head class="w-[100px]">Clase</Table.Head>
							<Table.Head class="w-[100px]"></Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if displayedParts.length === 0}
							<Table.Row>
								<Table.Cell colspan={5} class="text-center py-8 text-muted-foreground">
									No se encontraron números de parte
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each displayedParts as part}
								<Table.Row class="cursor-pointer hover:bg-muted/50" onclick={() => handleSelect(part)}>
									<Table.Cell class="font-medium">{part.part_number}</Table.Cell>
									<Table.Cell>{part.description_spanish || '-'}</Table.Cell>
									<Table.Cell class="text-muted-foreground">{part.description_english || '-'}</Table.Cell>
									<Table.Cell class="text-muted-foreground">{part.part_class || '-'}</Table.Cell>
									<Table.Cell>
										<Button variant="ghost" size="sm" class="h-8">
											Seleccionar
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
					</Table.Body>
				</Table.Root>
			{/if}
		</div>

		<Dialog.Footer class="mt-4">
			<p class="text-xs text-muted-foreground">
				Mostrando {displayedParts.length} de {filteredParts.length} resultados
			</p>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
