<script lang="ts">
	import { onMount, untrack } from 'svelte';
	import {
		getHistoricalFractions,
		deleteHistoricalFraction,
		type HistoricalFraction
	} from '$lib/api/dashboard/a76/general_catalogs/historical-tariff-fractions';
	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, Plus, Pencil, Trash2 } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import HistoricalFractionDialog from './HistoricalFractionDialog.svelte';

	import { companyStore } from '$lib/stores/company.svelte';

	let fractions = $state<HistoricalFraction[]>([]);
	let loading = $state(false);
	let historicalFraction = $state('');
	let page = $state(1);
	let totalItems = $state(0);
	let totalPages = $state(0);
	let pageSize = 50;

	let searchTimeout: ReturnType<typeof setTimeout>;
	let observer: IntersectionObserver;
	let sentinel: HTMLDivElement;

	// Infinite scroll state
	let hasMore = $state(true);

	// Dialog state
	let dialogOpen = $state(false);
	let editingFraction = $state<HistoricalFraction | null>(null);
	let deletingFractionId = $state<number | null>(null);

	async function loadFractions(reset = false) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		if (loading) return;

		loading = true;

		if (reset) {
			page = 1;
			fractions = [];
			hasMore = true;
		} else {
			page++;
		}

		try {
			const response = await getHistoricalFractions(
				companyId,
				historicalFraction || undefined,
				page,
				pageSize
			);

			const newItems = response.items || [];
			if (reset) {
				fractions = newItems;
			} else {
				fractions = [...fractions, ...newItems];
			}

			totalItems = response.total;
			totalPages = response.pages;

			// Safer end-of-data detection
			hasMore = newItems.length === pageSize && fractions.length < totalItems;
		} catch (error) {
			console.error('Error loading historical fractions:', error);
			toast.error('Error al cargar fracciones históricas');
			hasMore = false;
		} finally {
			loading = false;
		}
	}

	function handleSearch() {
		loadFractions(true);
	}

	function handleSearchInput() {
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			loadFractions(true);
		}, 500);
	}

	function handleKeyDown(event: KeyboardEvent) {
		if (event.key === 'Enter') {
			clearTimeout(searchTimeout);
			handleSearch();
		}
	}

	function handleCreate() {
		editingFraction = null;
		dialogOpen = true;
	}

	function handleEdit(fraction: HistoricalFraction) {
		editingFraction = fraction;
		dialogOpen = true;
	}

	async function handleDelete(fraction: HistoricalFraction) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		if (!confirm(`¿Estás seguro de eliminar la fracción ${fraction.historical_fraction}?`)) return;

		try {
			deletingFractionId = fraction.id;
			await deleteHistoricalFraction(companyId, fraction.id);
			toast.success('Fracción eliminada correctamente');
			loadFractions(true);
		} catch (error) {
			console.error('Error deleting historical fraction:', error);
			toast.error('Error al eliminar la fracción');
		} finally {
			deletingFractionId = null;
		}
	}

	function handleSuccess() {
		loadFractions(true);
	}

	function setupObserver() {
		if (observer) observer.disconnect();

		observer = new IntersectionObserver(
			(entries) => {
				if (entries[0].isIntersecting && hasMore && !loading && fractions.length > 0) {
					loadFractions(false);
				}
			},
			{ rootMargin: '100px' }
		);

		if (sentinel) observer.observe(sentinel);
	}

	// Removed onMount as we use $effect for company changes which covers initial load

	// Reload when company changes
	$effect(() => {
		const companyId = companyStore.activeCompany?.id;
		if (companyId) {
			untrack(() => loadFractions(true));
		}
	});

	// Setup observer only when sentinel is available
	$effect(() => {
		if (sentinel) {
			setupObserver();
			return () => observer?.disconnect();
		}
	});
</script>

<div class="space-y-4">
	<div class="flex flex-col items-end justify-between gap-4 md:flex-row">
		<div class="flex max-w-2xl flex-1 items-end gap-4">
			<div class="flex-1">
				<label for="search-fraction" class="mb-2 block text-sm font-medium"
					>Fracción Histórica</label
				>
				<div class="relative">
					<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
					<Input
						id="search-fraction"
						type="text"
						placeholder="Buscar fracción..."
						class="pl-9"
						bind:value={historicalFraction}
						oninput={handleSearchInput}
						onkeydown={handleKeyDown}
					/>
				</div>
			</div>
		</div>
		<Button onclick={handleCreate}>
			<Plus class="mr-2 h-4 w-4" />
			Nueva Fracción
		</Button>
	</div>

	<div class="rounded-md border">
		<Table.Root>
			<Table.Header>
				<Table.Row>
					<Table.Head>Fracción</Table.Head>
					<Table.Head>Tipo</Table.Head>
					<Table.Head>UM</Table.Head>
					<Table.Head>País</Table.Head>
					<Table.Head>Fecha Pub.</Table.Head>
					<Table.Head>Fecha Fin</Table.Head>
					<Table.Head class="text-right">IGI</Table.Head>
					<Table.Head class="text-right">IGE</Table.Head>
					<Table.Head class="w-[100px]">Acciones</Table.Head>
				</Table.Row>
			</Table.Header>
			<Table.Body>
				{#if fractions.length === 0 && !loading}
					<Table.Row>
						<Table.Cell colspan={9} class="h-24 text-center"
							>No se encontraron resultados</Table.Cell
						>
					</Table.Row>
				{:else}
					{#each fractions as fraction}
						<Table.Row>
							<Table.Cell class="font-medium">{fraction.historical_fraction}</Table.Cell>
							<Table.Cell>{fraction.fraction_type || '-'}</Table.Cell>
							<Table.Cell>{fraction.unit_of_measure_code || '-'}</Table.Cell>
							<Table.Cell>{fraction.country || '-'}</Table.Cell>
							<Table.Cell
								>{fraction.publication_date
									? new Date(fraction.publication_date).toLocaleDateString()
									: '-'}</Table.Cell
							>
							<Table.Cell
								>{fraction.end_date
									? new Date(fraction.end_date).toLocaleDateString()
									: '-'}</Table.Cell
							>
							<Table.Cell class="text-right">{fraction.import_tax_rate ?? '-'}</Table.Cell>
							<Table.Cell class="text-right">{fraction.export_tax_rate ?? '-'}</Table.Cell>
							<Table.Cell>
								<div class="flex items-center gap-2">
									<Button
										variant="ghost"
										size="icon"
										class="h-8 w-8"
										onclick={() => handleEdit(fraction)}
									>
										<Pencil class="h-4 w-4" />
									</Button>
									<Button
										variant="ghost"
										size="icon"
										class="h-8 w-8 text-destructive hover:text-destructive"
										onclick={() => handleDelete(fraction)}
										disabled={deletingFractionId === fraction.id}
									>
										{#if deletingFractionId === fraction.id}
											<Loader2 class="h-4 w-4 animate-spin" />
										{:else}
											<Trash2 class="h-4 w-4" />
										{/if}
									</Button>
								</div>
							</Table.Cell>
						</Table.Row>
					{/each}
				{/if}
				{#if loading}
					<Table.Row>
						<Table.Cell colspan={9} class="h-24 text-center">
							<div class="flex justify-center">
								<Loader2 class="h-6 w-6 animate-spin" />
							</div>
						</Table.Cell>
					</Table.Row>
				{/if}
			</Table.Body>
		</Table.Root>
	</div>

	<!-- Infinite Scroll Sentinel -->
	<div bind:this={sentinel} class="h-4 w-full"></div>

	<HistoricalFractionDialog
		bind:open={dialogOpen}
		fraction={editingFraction}
		onSuccess={handleSuccess}
	/>
</div>
