<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Search, Loader2, Download } from 'lucide-svelte';
	import {
		getTariffFractions,
		type TariffFraction
	} from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
	import { companyStore } from '$lib/stores/company.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaFracciones } from '$lib/config/shortcuts/dashboard/general_catalogs/tariff_fractions/list';
	import { onMount } from 'svelte';

	// Estado
	let tariffFractions = $state<TariffFraction[]>([]);
	let searchQuery = $state('');
	let isLoading = $state(false);
	let currentPage = $state(1);
	let totalPages = $state(1);
	let totalRecords = $state(0);
	const pageSize = 50;
	let searchTimeout: NodeJS.Timeout;

	// Atajos
	useShortcuts(
		'Lista Fracciones',
		obtenerAtajosListaFracciones({
			manejarNuevo: () => {}, // No hay botón de nuevo en esta vista
			manejarActualizar: () => loadTariffFractions(currentPage)
		})
	);

	onMount(() => {
		loadTariffFractions();
	});

	// Efecto para búsqueda con debounce
	$effect(() => {
		// Limpiar timeout anterior
		clearTimeout(searchTimeout);

		// Setup nuevo timeout
		searchTimeout = setTimeout(() => {
			// Resetear a página 1 cuando cambia la búsqueda
			if (currentPage !== 1) {
				currentPage = 1;
			}
			loadTariffFractions(1, searchQuery);
		}, 500);

		return () => clearTimeout(searchTimeout);
	});

	async function loadTariffFractions(page: number = 1, search: string = '') {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			console.error('No hay compañía activa');
			return;
		}

		isLoading = true;
		try {
			// Preparar filtros
			const filters: Record<string, any> = {};
			if (search.trim()) {
				filters.search = search.trim();
			}

			const response = await getTariffFractions(page, pageSize, companyId, filters);
			if (response.data) {
				tariffFractions = response.data.items;
				totalPages = response.data.pages;
				totalRecords = response.data.total;
				currentPage = response.data.page;
			}
		} catch (error) {
			console.error('Error cargando fracciones arancelarias:', error);
		} finally {
			isLoading = false;
		}
	}

	async function goToPage(page: number) {
		if (page >= 1 && page <= totalPages && page !== currentPage) {
			await loadTariffFractions(page, searchQuery);
		}
	}
</script>

<div class="container mx-auto p-6">
	<Card.Root>
		<Card.Header class="border-b text-center">
			<Card.Title class="text-2xl font-bold uppercase">
				Catálogo de Fracciones SITAR - SCAII
			</Card.Title>
			<p class="mt-2 text-muted-foreground">Nomenclatura arancelaria mexicana completa</p>
		</Card.Header>

		<Card.Content class="pt-6">
			<div class="space-y-6">
				<!-- Barra de búsqueda y acciones -->
				<div class="flex items-center gap-4">
					<div class="relative flex-1">
						<Search
							class="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground"
						/>
						<Input
							bind:value={searchQuery}
							placeholder="Buscar por código, fracción, descripción, NICO o UMT (Búsqueda en servidor)..."
							class="pl-9"
						/>
					</div>
					<Button variant="outline" size="icon" title="Exportar a CSV">
						<Download class="h-4 w-4" />
					</Button>
				</div>

				<!-- Información de registros -->
				<div class="flex items-center justify-between text-sm text-muted-foreground">
					<div>
						{#if isLoading}
							<div class="flex items-center gap-2">
								<Loader2 class="h-4 w-4 animate-spin" />
								<span>Cargando...</span>
							</div>
						{:else}
							Mostrando {tariffFractions.length} de {totalRecords} fracciones arancelarias
							{#if searchQuery}
								(filtrado)
							{/if}
						{/if}
					</div>
					{#if totalPages > 1}
						<div class="flex items-center gap-2">
							<span>Página {currentPage} de {totalPages}</span>
						</div>
					{/if}
				</div>

				<!-- Tabla de fracciones -->
				<div class="max-h-[600px] overflow-auto rounded-md border">
					<Table.Root>
						<Table.Header class="z-10 bg-background">
							<Table.Row>
								<Table.Head class="w-[100px]">Código</Table.Head>
								<Table.Head class="w-[120px]">Fracción</Table.Head>
								<Table.Head class="min-w-[350px]">Descripción</Table.Head>
								<Table.Head class="w-[80px]">NICO</Table.Head>
								<Table.Head class="w-[80px]">UMT</Table.Head>
								<Table.Head class="w-[100px]">Adv. Impo</Table.Head>
								<Table.Head class="w-[100px]">Adv. Expo</Table.Head>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{#if tariffFractions.length === 0}
								<Table.Row>
									<Table.Cell colspan={7} class="py-8 text-center text-muted-foreground">
										{#if isLoading}
											Cargando fracciones arancelarias...
										{:else if searchQuery}
											No se encontraron fracciones que coincidan con la búsqueda
										{:else}
											No hay fracciones arancelarias disponibles
										{/if}
									</Table.Cell>
								</Table.Row>
							{:else}
								{#each tariffFractions as fraction (fraction.id)}
									<Table.Row class="hover:bg-muted/50">
										<Table.Cell class="font-mono text-sm">{fraction.code}</Table.Cell>
										<Table.Cell class="font-mono text-sm font-medium"
											>{fraction.fraction}</Table.Cell
										>
										<Table.Cell class="text-sm">
											{fraction.description || '-'}
										</Table.Cell>
										<Table.Cell class="text-sm">{fraction.nico || '-'}</Table.Cell>
										<Table.Cell class="text-sm">{fraction.umt || '-'}</Table.Cell>
										<Table.Cell class="text-sm">{fraction.adv_impo || '-'}</Table.Cell>
										<Table.Cell class="text-sm">{fraction.adv_expo || '-'}</Table.Cell>
									</Table.Row>
								{/each}
							{/if}
						</Table.Body>
					</Table.Root>
				</div>

				<!-- Paginación -->
				{#if totalPages > 1}
					<div class="flex items-center justify-center gap-2">
						<Button
							variant="outline"
							size="sm"
							disabled={currentPage === 1 || isLoading}
							onclick={() => goToPage(1)}
						>
							Primera
						</Button>
						<Button
							variant="outline"
							size="sm"
							disabled={currentPage === 1 || isLoading}
							onclick={() => goToPage(currentPage - 1)}
						>
							Anterior
						</Button>
						<span class="px-4 text-sm">
							Página {currentPage} de {totalPages}
						</span>
						<Button
							variant="outline"
							size="sm"
							disabled={currentPage === totalPages || isLoading}
							onclick={() => goToPage(currentPage + 1)}
						>
							Siguiente
						</Button>
						<Button
							variant="outline"
							size="sm"
							disabled={currentPage === totalPages || isLoading}
							onclick={() => goToPage(totalPages)}
						>
							Última
						</Button>
					</div>
				{/if}
			</div>
		</Card.Content>
	</Card.Root>
</div>
