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

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

	let parts = $state<Part[]>([]);
	let searchPart = $state('');
	let currentPage = $state(1);
	let totalParts = $state(0);
	let hasMoreParts = $state(true);
	let isLoadingParts = $state(false);
	let searchTimeout: ReturnType<typeof setTimeout>;

	let wasOpen = $state(false);

	$effect(() => {
		if (open && !wasOpen) {
			searchPart = '';
			currentPage = 1;
			totalParts = 0;
			hasMoreParts = true;
			parts = [];
			loadParts('', 1);
		}
		wasOpen = open;
	});

	async function loadParts(search: string, page: number = currentPage) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId || isLoadingParts) return;

		isLoadingParts = true;
		try {
			const res = await partsApi.list({
				company_id: companyId,
				page: page,
				page_size: 50,
				q: search
			});

			if (res.data) {
				if (page === 1) {
					parts = [...res.data.items];
				} else {
					parts = [...parts, ...res.data.items];
				}
				totalParts = res.data.total;
				currentPage = page;
				hasMoreParts = parts.length < res.data.total;
			}
		} catch (error) {
			console.error('Error cargando partes:', error);
		} finally {
			isLoadingParts = false;
		}
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="z-[9999] w-full max-w-[95vw] sm:max-w-5xl">
		<Dialog.Header>
			<Dialog.Title>SELECCIONAR PARTE (SUSTITUTO)</Dialog.Title>
		</Dialog.Header>
		<div class="space-y-4">
			<div>
				<Label for="search_part">Buscar parte:</Label>
				<div class="relative mt-1">
					<Search class="absolute top-2.5 left-2 h-4 w-4 text-muted-foreground" />
					<Input
						id="search_part"
						bind:value={searchPart}
						placeholder="Número de parte o descripción..."
						class="pl-8"
						oninput={() => {
							clearTimeout(searchTimeout);
							searchTimeout = setTimeout(() => {
								parts = [];
								currentPage = 1;
								totalParts = 0;
								hasMoreParts = true;
								loadParts(searchPart, 1);
							}, 500);
						}}
					/>
				</div>
			</div>
			<div
				class="max-h-[500px] overflow-auto rounded-md border"
				onscroll={(e) => {
					const target = e.currentTarget;
					if (
						target.scrollHeight - target.scrollTop <= target.clientHeight + 50 &&
						hasMoreParts &&
						!isLoadingParts
					) {
						loadParts(searchPart, currentPage + 1);
					}
				}}
			>
				<table class="w-full text-sm">
					<thead class="sticky top-0 z-10 border-b bg-background">
						<tr>
							<th class="px-4 py-2 text-left font-semibold">No. Parte</th>
							<th class="px-4 py-2 text-left font-semibold">Descripción (ESP)</th>
							<th class="px-4 py-2 text-left font-semibold">U.M.</th>
						</tr>
					</thead>
					<tbody>
						{#each parts as part (part.id)}
							<tr
								class="cursor-pointer border-b transition-colors hover:bg-muted/50"
								onclick={() => {
									onSelect(part);
									open = false;
								}}
							>
								<td class="px-4 py-2 font-mono whitespace-nowrap">{part.part_number}</td>
								<td class="px-4 py-2">{part.description_spanish || '-'}</td>
								<td class="px-4 py-2 whitespace-nowrap">{part.unit_of_measure}</td>
							</tr>
						{:else}
							<tr>
								<td colspan="3" class="px-4 py-8 text-center text-muted-foreground">
									{#if isLoadingParts}
										<div class="flex items-center justify-center gap-2">
											<Loader2 class="h-4 w-4 animate-spin" />
											Buscando partes...
										</div>
									{:else}
										No se encontraron partes
									{/if}
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
			{#if isLoadingParts && parts.length > 0}
				<div class="flex justify-center py-2">
					<Loader2 class="h-4 w-4 animate-spin text-muted-foreground" />
				</div>
			{/if}
		</div>
		<div class="flex justify-end gap-2 pt-4">
			{#if onClear}
				<Button variant="ghost" class="mr-auto" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>
