<script lang="ts">
	import { 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 * as Card from '$lib/components/ui/card';
	import { Search, Loader2, Plus, Pencil, Trash2 } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import HistoricalFractionDialog from './HistoricalFractionDialog.svelte';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import {
		canCreateTariffFractionCatalog,
		canDeleteTariffFractionCatalog,
		canEditTariffFractionCatalog,
		canViewTariffFractionCatalog
	} from '$lib/permissions/tariff-fraction-permissions';

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

	let { title = 'Fracciones históricas' }: { title?: string } = $props();

	const FRAC_HIST = 'frac_historical';

	// Permisos
	const canView = $derived(canViewTariffFractionCatalog($currentUser, FRAC_HIST));
	const canCreate = $derived(canCreateTariffFractionCatalog($currentUser, FRAC_HIST));
	const canEdit = $derived(canEditTariffFractionCatalog($currentUser, FRAC_HIST));
	const canDelete = $derived(canDeleteTariffFractionCatalog($currentUser, FRAC_HIST));

	let fractions = $state<HistoricalFraction[]>([]);
	let loading = $state(false);
	let error = $state<string | null>(null);
	let status = $state<number>(200);
	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 = $state<HTMLDivElement | null>(null);
let scrollContainer = $state<HTMLDivElement | null>(null);

	// 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() {
		if (!canCreate) {
			toast.error('No tienes permiso para crear fracciones históricas');
			return;
		}
		editingFraction = null;
		dialogOpen = true;
	}

	function handleEdit(fraction: HistoricalFraction) {
		if (!canEdit) {
			toast.error('No tienes permiso para editar fracciones históricas');
			return;
		}
		editingFraction = fraction;
		dialogOpen = true;
	}

	async function handleDelete(fraction: HistoricalFraction) {
		if (!canDelete) {
			toast.error('No tienes permiso para eliminar fracciones históricas');
			return;
		}
		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);
				}
			},
			{
				root: scrollContainer || null,
				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="flex flex-col gap-6 p-6 h-[calc(100svh-4rem)] group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)] overflow-hidden">
	<div class="flex items-center justify-between gap-4">
		<div class="space-y-1">
			<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
			<p class="text-sm text-muted-foreground">
				Gestiona las fracciones históricas de la tarifa.
			</p>
		</div>
		{#if canView && canCreate}
			<Button class="h-9" onclick={handleCreate}>
				<Plus class="mr-2 h-4 w-4" />
				Nueva Fracción
			</Button>
		{/if}
	</div>

	{#if !canView}
		<ErrorState status={403} error="No tienes permiso para ver este catálogo" onRetry={() => loadFractions(true)} />
	{:else}

		<Card.Root class="flex min-h-0 flex-1 flex-col border bg-background">
			<Card.Header>
				<div class="flex flex-wrap items-center justify-end gap-3">
					<div class="flex flex-wrap items-center gap-2">
						<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="h-9 w-40 bg-card pl-9 lg:w-56"
								bind:value={historicalFraction}
								oninput={handleSearchInput}
								onkeydown={handleKeyDown}
							/>
						</div>
					</div>
				</div>
			</Card.Header>
			<Card.Content class="min-h-0 p-0">
				<div class="catalog-table-shell flex min-h-0 flex-1 flex-col overflow-hidden">
					<div class="min-h-[360px] max-h-[calc(100svh-340px)] flex-1 overflow-y-auto" bind:this={scrollContainer}>
						<Table.Root>
							<Table.Header class="catalog-table-header">
								<Table.Row>
									<Table.Head class="catalog-table-head-cell">Fracción</Table.Head>
									<Table.Head class="catalog-table-head-cell">Tipo</Table.Head>
									<Table.Head class="catalog-table-head-cell">UM</Table.Head>
									<Table.Head class="catalog-table-head-cell">País</Table.Head>
									<Table.Head class="catalog-table-head-cell">Fecha Pub.</Table.Head>
									<Table.Head class="catalog-table-head-cell">Fecha Fin</Table.Head>
									<Table.Head class="catalog-table-head-cell text-right">IGI</Table.Head>
									<Table.Head class="catalog-table-head-cell text-right">IGE</Table.Head>
									{#if canEdit || canDelete}
										<Table.Head class="catalog-table-head-cell w-[100px]">Acciones</Table.Head>
									{/if}
								</Table.Row>
							</Table.Header>
							<Table.Body>
								{#if fractions.length === 0 && !loading}
									<Table.Row>
										<Table.Cell colspan={canEdit || canDelete ? 9 : 8} class="h-24 text-center">No se encontraron resultados</Table.Cell>
									</Table.Row>
								{:else}
									{#each fractions as fraction}
										<Table.Row class="catalog-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>
											{#if canEdit || canDelete}
												<Table.Cell>
													<div class="flex items-center gap-2">
														{#if canEdit}
															<Button variant="ghost" size="icon" class="h-8 w-8" onclick={() => handleEdit(fraction)}>
																<Pencil class="h-4 w-4" />
															</Button>
														{/if}
														{#if canDelete}
															<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>
														{/if}
													</div>
												</Table.Cell>
											{/if}
										</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 bind:this={sentinel} class="h-4 w-full"></div>
				</div>
			</div>
		</Card.Content>
	</Card.Root>

	<div class="flex-none text-sm text-muted-foreground">Mostrando {fractions.length} de {totalItems} registros</div>

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