<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Button } from '$lib/components/ui/button';
	import { Label } from '$lib/components/ui/label';
	import {
		Table,
		TableBody,
		TableCell,
		TableHead,
		TableHeader,
		TableRow
	} from '$lib/components/ui/table';
	import { Loader2, Plus, Search, Trash2, Edit } from 'lucide-svelte';
	import {
		getTariffFractions,
		deleteTariffFraction,
		type TariffFraction
	} from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
	import { companyStore } from '$lib/stores/company.svelte';
	import { onMount, untrack } from 'svelte';
	import * as AlertDialog from '$lib/components/ui/alert-dialog';
	import TariffFractionFormDialog from './TariffFractionFormDialog.svelte';
	import { toast } from 'svelte-sonner';

	let {
		title = 'Fracciones Arancelarias',
		catalog = 'mex', // 'mex' or 'usa'
		levelFilter = null, // null or number
		readOnly = false
	}: {
		title?: string;
		catalog?: string;
		levelFilter?: number | null;
		readOnly?: boolean;
	} = $props();

	let fractions = $state<TariffFraction[]>([]);
	let totalFractions = $state(0);
	let currentPage = $state(1);
	let pageSize = 50;
	let isLoading = $state(false);
	let search = $state('');
	let searchTimeout: ReturnType<typeof setTimeout>;
	let observer: IntersectionObserver;
	let sentinel: HTMLDivElement;

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

	let isFormDialogOpen = $state(false);
	let selectedFraction = $state<TariffFraction | null>(null);
	let isManageMode = $state(false); // If true, opens form in edit mode

	// Delete confirmation
	let showDeleteConfirm = $state(false);
	let fractionToDelete = $state<TariffFraction | null>(null);

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

		isLoading = true;

		if (reset) {
			currentPage = 1;
			fractions = [];
			hasMore = true;
		}

		try {
			const filters: Record<string, any> = {};
			if (search) filters.search = search;
			if (levelFilter !== null) filters.level = levelFilter;
			filters.catalog = catalog;

			const response = await getTariffFractions(currentPage, pageSize, companyId, filters);

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

				// Safer end-of-data detection
				hasMore = newItems.length === pageSize && fractions.length < totalFractions;
			} else {
				if (reset) fractions = [];
				hasMore = false;
			}
		} catch (error) {
			console.error('Error loading fractions:', error);
			toast.error('Error al cargar las fracciones');
			hasMore = false;
		} finally {
			isLoading = false;
		}
	}

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

	function handlePageChange(newPage: number) {
		currentPage = newPage;
		loadFractions();
	}

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

		observer = new IntersectionObserver(
			(entries) => {
				if (entries[0].isIntersecting && hasMore && !isLoading && fractions.length > 0) {
					handlePageChange(currentPage + 1);
				}
			},
			{ rootMargin: '100px' }
		);

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

	function openCreateDialog() {
		selectedFraction = null;
		isManageMode = false; // Create mode
		isFormDialogOpen = true;
	}

	function openEditDialog(fraction: TariffFraction) {
		selectedFraction = fraction;
		isManageMode = true; // Edit mode
		isFormDialogOpen = true;
	}

	function confirmDelete(fraction: TariffFraction) {
		fractionToDelete = fraction;
		showDeleteConfirm = true;
	}

	async function handleDelete() {
		if (!fractionToDelete || !companyStore.activeCompany?.id) return;

		try {
			// Note: Delete might allow deleting items from source API if allowed,
			// or just local overrides. Assuming Service handles logic.
			await deleteTariffFraction(fractionToDelete.id, companyStore.activeCompany.id, catalog);
			toast.success('Fracción eliminada correctamente');
			loadFractions(true);
		} catch (error) {
			console.error('Error deleting fraction:', error);
			toast.error('Error al eliminar la fracción. Puede que esté en uso.');
		} finally {
			showDeleteConfirm = false;
			fractionToDelete = null;
		}
	}
	// 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 p-4">
	<div class="flex items-center justify-between">
		<h2 class="text-2xl font-bold tracking-tight">{title}</h2>
		{#if !readOnly}
			<Button onclick={openCreateDialog}>
				<Plus class="mr-2 h-4 w-4" />
				Nueva Fracción
			</Button>
		{/if}
	</div>

	<div class="flex items-center space-x-2">
		<div class="relative max-w-sm flex-1">
			<Search class="absolute top-2.5 left-2 h-4 w-4 text-muted-foreground" />
			<Input placeholder="Buscar..." class="pl-8" bind:value={search} oninput={handleSearchInput} />
		</div>
	</div>

	<div class="rounded-md border">
		<Table>
			<TableHeader>
				<TableRow>
					<TableHead>Clave</TableHead>
					<TableHead>Fracción</TableHead>
					<TableHead>Descripción</TableHead>
					{#if catalog === 'mex'}
						<TableHead>NICO</TableHead>
						<TableHead>U.M.T</TableHead>
					{:else}
						<TableHead>Unidad</TableHead>
					{/if}
					<TableHead>Adv. Impo</TableHead>
					<TableHead>Adv. Expo</TableHead>
					{#if !readOnly}
						<TableHead class="w-[100px]">Acciones</TableHead>
					{/if}
				</TableRow>
			</TableHeader>
			<TableBody>
				{#if fractions.length === 0 && !isLoading}
					<TableRow>
						<TableCell
							colspan={catalog === 'mex' ? (readOnly ? 7 : 8) : readOnly ? 6 : 7}
							class="h-24 text-center"
						>
							No se encontraron resultados
						</TableCell>
					</TableRow>
				{:else}
					{#each fractions as fraction}
						<TableRow>
							<TableCell class="font-mono">{fraction.um_code || fraction.code}</TableCell>
							<TableCell class="font-medium">{fraction.fraction}</TableCell>
							<TableCell class="max-w-md truncate" title={fraction.description}>
								{fraction.description}
							</TableCell>
							{#if catalog === 'mex'}
								<TableCell>{fraction.nico || '-'}</TableCell>
								<TableCell>{fraction.umt || '-'}</TableCell>
							{:else}
								<TableCell>{fraction.umt || '-'}</TableCell>
							{/if}
							<TableCell>{fraction.adv_impo || '-'}</TableCell>
							<TableCell>{fraction.adv_expo || '-'}</TableCell>
							{#if !readOnly}
								<TableCell>
									<div class="flex items-center gap-2">
										<Button variant="ghost" size="icon" onclick={() => openEditDialog(fraction)}>
											<Edit class="h-4 w-4" />
										</Button>
										<Button
											variant="ghost"
											size="icon"
											class="text-destructive hover:text-destructive"
											onclick={() => confirmDelete(fraction)}
										>
											<Trash2 class="h-4 w-4" />
										</Button>
									</div>
								</TableCell>
							{/if}
						</TableRow>
					{/each}
				{/if}
				{#if isLoading}
					<TableRow>
						<TableCell
							colspan={catalog === 'mex' ? (readOnly ? 7 : 8) : readOnly ? 6 : 7}
							class="h-24 text-center"
						>
							<div class="flex justify-center">
								<Loader2 class="h-6 w-6 animate-spin" />
							</div>
						</TableCell>
					</TableRow>
				{/if}
			</TableBody>
		</Table>
	</div>

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

<AlertDialog.Root bind:open={showDeleteConfirm}>
	<AlertDialog.Content>
		<AlertDialog.Header>
			<AlertDialog.Title>¿Estás seguro?</AlertDialog.Title>
			<AlertDialog.Description>
				Esta acción no se puede deshacer. Se eliminará la fracción arancelaria permanentemente.
			</AlertDialog.Description>
		</AlertDialog.Header>
		<AlertDialog.Footer>
			<AlertDialog.Cancel>Cancelar</AlertDialog.Cancel>
			<AlertDialog.Action
				class="text-destructive-foreground bg-destructive hover:bg-destructive/90"
				onclick={handleDelete}
			>
				Eliminar
			</AlertDialog.Action>
		</AlertDialog.Footer>
	</AlertDialog.Content>
</AlertDialog.Root>

{#if isFormDialogOpen}
	<TariffFractionFormDialog
		bind:open={isFormDialogOpen}
		fraction={selectedFraction}
		{catalog}
		onSuccess={() => {
			loadFractions(true);
			isFormDialogOpen = false;
		}}
	/>
{/if}
