<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import { getDodas, deleteDoda, type Doda } from '$lib/api/dashboard/a76/general_catalogs/doda';
	import * as Card from '$lib/components/ui/card';
	import { toast } from 'svelte-sonner';
	import {
		Plus,
		RefreshCw,
		Trash2,
		Pencil,
		Search,
		RotateCcw,
		FileText,
		LayoutGrid,
		Printer
	} from 'lucide-svelte';
	import * as Select from '$lib/components/ui/select';
	import { companyStore } from '$lib/stores/company.svelte';
	import DataTable from '$lib/components/dashboard/general_catalogs/doda/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/doda/columns';
	import CreateEditDialog from '$lib/components/dashboard/general_catalogs/doda/create-edit-dialog.svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Separator } from '$lib/components/ui/separator';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaDoda } from '$lib/config/shortcuts/dashboard/general_catalogs/doda/list';

	let { data } = $props();
	let dialogOpen = $state(false);

	// Filtros centralizados
	let filters = $state({
		integration_number: $page.url.searchParams.get('integration_number') || '',
		patent: $page.url.searchParams.get('patent') || '',
		status: $page.url.searchParams.get('status') || '',
		operation_type: $page.url.searchParams.get('operation_type') || ''
	});

	let timeout: ReturnType<typeof setTimeout>;

	// State for infinite scroll
	let allItems = $state<Doda[]>(data.dodas?.items || []);
	let currentPage = $state(data.dodas?.page || 1);
	let pageSize = $state(50);
	let totalItems = $state(data.dodas?.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);
	let error = $state<string | null>(data.error || null);

	// Selection
	let selectedId = $state<number | null>(null);
	const selectedDoda = $derived(selectedId ? allItems.find((i) => i.id === selectedId) : null);

	// Sincronizar con datos del servidor al cargar (primera carga)
	$effect(() => {
		if (data.dodas) {
			allItems = data.dodas.items || [];
			currentPage = data.dodas.page || 1;
			totalItems = data.dodas.total || 0;
		}
	});

	// Sincronizar filtros con la URL de forma reactiva
	$effect(() => {
		if (browser) {
			const params = new URLSearchParams();
			if (filters.integration_number) params.set('integration_number', filters.integration_number);
			if (filters.patent) params.set('patent', filters.patent);
			if (filters.status) params.set('status', filters.status);
			if (filters.operation_type) params.set('operation_type', filters.operation_type);

			const queryString = params.toString();
			const newUrl = queryString ? `?${queryString}` : window.location.pathname;

			if (window.location.search !== (queryString ? `?${queryString}` : '')) {
				window.history.replaceState({}, '', newUrl);
			}
		}
	});

	// Disparar recarga cuando cambian los filtros (con debounce)
	$effect(() => {
		// Observamos todos los campos de filtros
		const _ = { ...filters };

		clearTimeout(timeout);
		timeout = setTimeout(() => {
			reloadData();
		}, 400);
	});

	// Atajos
	useShortcuts(
		'Lista DODA',
		obtenerAtajosListaDoda({
			manejarNuevo: handleCreateClick,
			manejarActualizar: reloadData
		})
	);

	async function loadMore() {
		if (loading || !hasMore) return;

		loading = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) return;

			// Limpiar filtros vacíos
			const activeFilters = Object.fromEntries(
				Object.entries(filters).filter(([_, v]) => v !== '')
			);

			const res = await getDodas(currentPage + 1, pageSize, activeFilters, Number(companyId));

			if (res.data) {
				allItems = [...allItems, ...res.data.items];
				currentPage++;
				totalItems = res.data.total;
			}
		} catch (e) {
			console.error('Error loading more DODAs:', e);
		} finally {
			loading = false;
		}
	}

	async function reloadData() {
		if (!browser) return;
		loading = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) return;

			const activeFilters = Object.fromEntries(
				Object.entries(filters).filter(([_, v]) => v !== '')
			);

			const res = await getDodas(1, pageSize, activeFilters, Number(companyId));

			if (res.data) {
				allItems = res.data.items;
				currentPage = 1;
				totalItems = res.data.total;
				selectedId = null;
			}
		} catch (e) {
			console.error('Error reloading DODAs:', e);
			// Evitar mostrar error si es solo carga inicial y falla por falta de login etc
			if (allItems.length > 0) toast.error('Error al recargar datos');
		} finally {
			loading = false;
		}
	}

	function clearFilters() {
		filters = {
			integration_number: '',
			patent: '',
			status: '',
			operation_type: ''
		};
	}

	function handleCreateClick() {
		goto('/dashboard/general_catalogs/doda/edit');
	}

	function handleEdit() {
		if (selectedId) {
			goto(`/dashboard/general_catalogs/doda/edit/${selectedId}`);
		}
	}

	async function handleDelete() {
		if (!selectedId || !companyStore.activeCompany) return;

		if (confirm('¿Estás seguro de eliminar este DODA?')) {
			try {
				await deleteDoda(selectedId, companyStore.activeCompany.id);
				toast.success('DODA eliminado correctamente');
				reloadData();
			} catch (e) {
				toast.error('Error al eliminar DODA');
			}
		}
	}

	function handleRowClick(doda: Doda) {
		selectedId = selectedId === doda.id ? null : doda.id;
	}
</script>

<div class="space-y-6">
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-3xl font-bold tracking-tight">DODA</h1>
			<p class="text-muted-foreground">Gestiona tus Documentos de Operación Aduanera (DODA)</p>
		</div>
		<Button onclick={handleCreateClick} class="shadow-sm transition-all hover:translate-y-[-1px]">
			<Plus class="mr-2 h-4 w-4" />
			Nuevo DODA
		</Button>
	</div>

	<Card.Root>
		<Card.Header>
			<div class="flex items-center justify-between">
				<div>
					<Card.Title>Filtros Avanzados</Card.Title>
					<Card.Description>Refina tu búsqueda mediante múltiples criterios</Card.Description>
				</div>
				<Button variant="ghost" size="sm" onclick={clearFilters} class="text-muted-foreground">
					<RotateCcw class="mr-2 h-4 w-4" />
					Limpiar Filtros
				</Button>
			</div>
		</Card.Header>
		<Card.Content>
			<div class="grid grid-cols-1 gap-4 md:grid-cols-4">
				<div class="space-y-2">
					<Label for="search-integration">No. Integración</Label>
					<div class="relative">
						<Search class="absolute top-2.5 left-2.5 h-4 w-4 text-muted-foreground" />
						<Input
							id="search-integration"
							placeholder="Buscar integración..."
							bind:value={filters.integration_number}
							class="pl-9"
						/>
					</div>
				</div>

				<div class="space-y-2">
					<Label for="search-patent">Patente</Label>
					<Input id="search-patent" placeholder="Buscar patente..." bind:value={filters.patent} />
				</div>

				<div class="space-y-2">
					<Label>Estatus</Label>
					<Select.Root
						type="single"
						value={filters.status}
						onValueChange={(v) => (filters.status = v)}
					>
						<Select.Trigger class="w-full">
							{filters.status || 'Todos los estatus'}
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="">Todos</Select.Item>
							<Select.Item value="PENDIENTE">PENDIENTE</Select.Item>
							<Select.Item value="GENERADO">GENERADO</Select.Item>
							<Select.Item value="VALIDADO">VALIDADO</Select.Item>
							<Select.Item value="ELIMINADO">ELIMINADO</Select.Item>
						</Select.Content>
					</Select.Root>
				</div>

				<div class="space-y-2">
					<Label>Operación</Label>
					<Select.Root
						type="single"
						value={filters.operation_type}
						onValueChange={(v) => (filters.operation_type = v)}
					>
						<Select.Trigger class="w-full">
							{filters.operation_type === 'I'
								? 'Importación'
								: filters.operation_type === 'E'
									? 'Exportación'
									: 'Todas'}
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="">Todas</Select.Item>
							<Select.Item value="I">I - Importación</Select.Item>
							<Select.Item value="E">E - Exportación</Select.Item>
						</Select.Content>
					</Select.Root>
				</div>
			</div>
		</Card.Content>
	</Card.Root>

	<Card.Root>
		<Card.Header>
			<div class="flex items-center justify-between">
				<div>
					<Card.Title>Listado de DODAs</Card.Title>
					<Card.Description>
						Mostrando {allItems.length} de {totalItems} registros
					</Card.Description>
				</div>
				<Button variant="outline" size="sm" onclick={reloadData} disabled={loading}>
					<RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />
					Actualizar
				</Button>
			</div>
		</Card.Header>
		<Card.Content class="p-0">
			<DataTable
				data={allItems}
				columns={createColumns(reloadData)}
				{loading}
				{hasMore}
				{loadMore}
				{selectedId}
				onRowClick={handleRowClick}
			/>
		</Card.Content>
	</Card.Root>

	<!-- Footer fijo de acciones (estilo Facturas) -->
	<div
		class="fixed right-0 bottom-0 left-0 z-50 ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
	>
		<div class="mx-auto max-w-[1400px] px-4 py-4">
			<div class="flex items-center justify-between">
				<div class="text-sm text-muted-foreground">
					{#if selectedDoda}
						Seleccionado: <span class="font-medium text-foreground"
							>{selectedDoda.integration_number || 'S/N'}</span
						>
					{:else}
						Selecciona un registro para ver acciones
					{/if}
				</div>
				<div class="flex gap-2">
					<Button variant="outline" size="sm" onclick={reloadData} disabled={loading}>
						<RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />
						Actualizar
					</Button>

					<Button variant="outline" size="sm" onclick={handleEdit} disabled={!selectedId}>
						<Pencil class="mr-2 h-4 w-4" />
						Editar
					</Button>

					<Button variant="destructive" size="sm" onclick={handleDelete} disabled={!selectedId}>
						<Trash2 class="mr-2 h-4 w-4" />
						Eliminar
					</Button>

					<Separator orientation="vertical" class="mx-1 h-8" />

					<Button variant="secondary" size="sm" disabled={!selectedId}>
						<Printer class="mr-2 h-4 w-4" />
						Imprimir
					</Button>
				</div>
			</div>
		</div>
	</div>
</div>

<div class="h-20"></div>
<!-- Espacio buffer para el footer -->

{#if dialogOpen}
	<CreateEditDialog bind:open={dialogOpen} onSuccess={reloadData} />
{/if}
