<script lang="ts">
	import { onMount } from 'svelte';
	import { incotermsApi, type Incoterm } from '$lib/api/dashboard/reference_data/incoterms';
	import DataTable from '$lib/components/dashboard/reference_data/incoterms/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/reference_data/incoterms/columns';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { RefreshCw, Plus } from 'lucide-svelte';
	import { page } from '$app/stores';
	import type { PageData } from './$types';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosLista } from '$lib/config/shortcuts/dashboard/reference_data/incoterms/list';
	import { browser } from '$app/environment';
	import { currentUser } from '$lib/auth';
	import { userHasIncotermsRefAction } from '$lib/permissions/reference-data/incoterms-ref-permissions';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	// Los datos iniciales vienen del servidor
	let { data }: { data: PageData } = $props();
	
	// Atajos
	useShortcuts(
		'Lista Incoterms',
		obtenerAtajosLista({
			manejarActualizar: reloadData
		})
	);

	// Estado para infinite scroll
	let allItems = $state<Incoterm[]>(data.items || []);
	let currentPage = $state(data.page || 1);
	let pageSize = $state(data.page_size || 50);
	let totalItems = $state(data.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

	// Permisos
	const canView = $derived(userHasIncotermsRefAction($currentUser, 'view'));
	const canCreate = $derived(false);
	const canEdit = $derived(false);
	const canDelete = $derived(false);

	const isError = $derived(!canView || status >= 400 || error);

	// Filtros de búsqueda (Código y Descripción)
	let searchCode = $state($page.url.searchParams.get('code') || '');
	let searchDescription = $state($page.url.searchParams.get('description') || '');
	let timeout: ReturnType<typeof setTimeout>;

	function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(async () => {
			loading = true;
			error = null;
			try {
				const response = await incotermsApi.list(1, pageSize, searchCode, searchDescription);
				if (!response.error && response.data) {
					allItems = response.data.items;
					currentPage = 1;
					totalItems = response.data.total;
				}
			} catch (e) {
				console.error('Error aplicando filtros:', e);
			} finally {
				loading = false;
			}
			
			const url = new URL($page.url);
			if (searchCode) url.searchParams.set('code', searchCode);
			else url.searchParams.delete('code');
			
			if (searchDescription) url.searchParams.set('description', searchDescription);
			else url.searchParams.delete('description');
			
			history.replaceState(history.state, '', url);
		}, 500);
	}

	async function loadMore() {
		if (loading || !hasMore) return;
		loading = true;
		error = null;
		try {			
			const response = await incotermsApi.list(currentPage + 1, pageSize, searchCode, searchDescription);
			if (response.error) {
				if (response.status === 401 || response.status === 403) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => window.location.reload(), 2000);
				} else {
					error = response.error;
				}
				return;
			}
			if (response.data?.items) {				
				allItems = [...allItems, ...response.data.items];
				currentPage++;
				totalItems = response.data.total;
			}
		} catch (e) {
			error = 'Error cargando más datos';
			console.error('📊 [Incoterms] Error loading more:', e);
		} finally {
			loading = false;
		}
	}

	function reloadData() {
		if (browser) window.location.reload();
	}

	function handleSuccess() {
		reloadData();
	}

	// Crear columnas
	const columns = $derived(createColumns(handleSuccess, { canEdit, canDelete }));
</script>

{#if isError}
	<div
		class="flex h-[calc(100svh-4rem)] flex-col p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]"
	>
		<ErrorState
			status={!canView ? 403 : status}
			error={!canView ? 'Permission denied: ref_incoterms.view' : error || ''}
			onRetry={reloadData}
		/>
	</div>
{:else}
	<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">
		{#if error}
			<div class="flex-none rounded-md border border-destructive px-4 py-3 text-sm text-destructive">
				{error}
			</div>
		{/if}

		<Card.Root class="border bg-background flex min-h-0 flex-1 flex-col overflow-hidden">
			<Card.Header>
				<div class="flex flex-wrap items-center justify-between gap-3">
					<Card.Title>Listado de Incoterms</Card.Title>
					<div class="flex flex-wrap items-center gap-2">
						<Input placeholder="Código" bind:value={searchCode} oninput={handleSearch} class="h-9 w-32 bg-card lg:w-40" />
						<Input placeholder="Descripción" bind:value={searchDescription} oninput={handleSearch} class="h-9 w-44 bg-card lg:w-64" />
					</div>
				</div>
			</Card.Header>
			<Card.Content class="min-h-0 p-0 flex-1 overflow-hidden flex flex-col">
				<div class="rounded-md border bg-background overflow-hidden flex-1 h-full">
					<DataTable data={allItems} {columns} {loading} {hasMore} {loadMore} />
				</div>
			</Card.Content>
		</Card.Root>

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