<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, FileText } from 'lucide-svelte';
	import { pedimentosApi, type Pedimento } from '$lib/api/dashboard/a76/pedimentos';
	import { companyStore } from '$lib/stores/company.svelte';

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

	let pedimentos = $state<Pedimento[]>([]);
	let loading = $state(false);
	let loadingMore = $state(false);
	let searchTerm = $state('');
	let loaded = $state(false);
	let page = $state(1);
	let pageSize = 50;
	let totalItems = $state(0);
	let hasMore = $state(true);
	let observer: IntersectionObserver | null = null;
	let bottomSentinel: HTMLElement | null = $state(null);
	let scrollContainer: HTMLDivElement | null = $state(null);

	function buildPedimentoLabel(pedimento: Pedimento): string {
		return `${pedimento.customs_office?.slice(0, 2) || ''}-${pedimento.license || ''}-${pedimento.pedimento_number || ''}`.replace(
			/^-+|-+$/g,
			''
		);
	}

	let filteredPedimentos = $derived(
		pedimentos.filter((pedimento) => {
			const label = buildPedimentoLabel(pedimento).toLowerCase();
			const code = (pedimento.pedimento_code || '').toLowerCase();
			const regime = (pedimento.regime || '').toLowerCase();
			const status = (pedimento.status || '').toLowerCase();
			const term = searchTerm.toLowerCase();
			return (
				label.includes(term) ||
				code.includes(term) ||
				regime.includes(term) ||
				status.includes(term) ||
				pedimento.id.toString().includes(searchTerm)
			);
		})
	);

	$effect(() => {
		if (open && !loaded && companyStore.activeCompany?.id) {
			void resetAndLoad();
		} else if (!open) {
			loaded = false;
			page = 1;
			hasMore = true;
			totalItems = 0;
			pedimentos = [];
		}
	});

	$effect(() => {
		if (bottomSentinel && scrollContainer && hasMore && !loading && !loadingMore && open) {
			if (observer) observer.disconnect();

			observer = new IntersectionObserver(
				(entries) => {
					if (entries[0].isIntersecting && hasMore && !loading && !loadingMore) {
						void loadMore();
					}
				},
				{
					root: scrollContainer,
					threshold: 0.1
				}
			);

			observer.observe(bottomSentinel);
		}

		return () => {
			if (observer) observer.disconnect();
		};
	});

	async function resetAndLoad() {
		page = 1;
		hasMore = true;
		totalItems = 0;
		pedimentos = [];
		await loadPedimentos(true);
	}

	async function loadMore() {
		if (!hasMore || loading || loadingMore) return;
		page += 1;
		await loadPedimentos(false);
	}

	async function loadPedimentos(isInitial: boolean) {
		if (!companyStore.activeCompany?.id) return;

		if (isInitial) loading = true;
		else loadingMore = true;
		try {
			const res = await pedimentosApi.list(page, pageSize, undefined, companyStore.activeCompany.id);
			const responseData = (res as any).data || res;
			if (responseData?.items) {
				const newItems = responseData.items as Pedimento[];
				totalItems = responseData.total || 0;
				pedimentos = isInitial ? newItems : [...pedimentos, ...newItems];
				hasMore = pedimentos.length < totalItems && newItems.length > 0;
				loaded = true;
			} else {
				hasMore = false;
			}
		} catch (e) {
			console.error('Error cargando pedimentos:', e);
			hasMore = false;
		} finally {
			loading = false;
			loadingMore = false;
		}
	}

	function handleSelect(pedimento: Pedimento) {
		onSelect?.(pedimento);
		open = false;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[900px] max-h-[80vh] flex flex-col z-[300]">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Pedimento</Dialog.Title>
			<Dialog.Description>
				Busca y selecciona el pedimento registrado para asociarlo a la digitalización.
			</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 pedimento, clave, régimen o ID..."
				class="pl-9"
				bind:value={searchTerm}
			/>
		</div>

		<div bind:this={scrollContainer} class="flex-1 overflow-y-auto border rounded-md min-h-[300px]">
			{#if loading && pedimentos.length === 0}
				<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 filteredPedimentos.length === 0}
				<div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
					<p>No se encontraron pedimentos.</p>
				</div>
			{:else}
				<table class="w-full text-sm">
					<thead class="bg-muted/50 backdrop-blur-sm">
						<tr class="text-left border-b">
							<th class="p-3 font-medium text-muted-foreground w-[60px]">ID</th>
							<th class="p-3 font-medium text-muted-foreground w-[220px]">Pedimento</th>
							<th class="p-3 font-medium text-muted-foreground w-[120px]">Clave</th>
							<th class="p-3 font-medium text-muted-foreground">Régimen</th>
							<th class="p-3 font-medium text-muted-foreground w-[110px] text-center">Estado</th>
						</tr>
					</thead>
					<tbody>
						{#each filteredPedimentos as pedimento}
							<tr
								class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
								onclick={() => handleSelect(pedimento)}
							>
								<td class="p-3 font-mono text-xs">{pedimento.id}</td>
								<td class="p-3 font-medium">
									<div class="flex items-center gap-2">
										<FileText class="h-3 w-3 text-blue-500" />
										<span class="font-mono text-xs">{buildPedimentoLabel(pedimento)}</span>
									</div>
								</td>
								<td class="p-3 font-mono text-xs">{pedimento.pedimento_code || '-'}</td>
								<td class="p-3">{pedimento.regime || '-'}</td>
								<td class="p-3 text-center">
									{#if pedimento.status}
										<span class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800">
											{pedimento.status}
										</span>
									{:else}
										<span class="inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-700">
											Sin estado
										</span>
									{/if}
								</td>
							</tr>
						{/each}
					</tbody>
				</table>

				<div bind:this={bottomSentinel} class="flex h-10 items-center justify-center">
					{#if loadingMore}
						<Loader2 class="h-5 w-5 animate-spin text-muted-foreground" />
					{/if}
				</div>
			{/if}
		</div>

		<Dialog.Footer>
			<div class="text-xs text-muted-foreground self-center mr-auto">
				Mostrando {filteredPedimentos.length} de {totalItems || pedimentos.length} registro(s) cargados
			</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>