<script lang="ts">
	import { onMount } from 'svelte';
	import {
		manifestApi,
		type Manifest,
		type ManifestResponse
	} from '$lib/api/dashboard/a76/manifests';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Plus, RefreshCw, FileText, Search, Package, Calendar } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';

	import DataTable from '$lib/components/dashboard/export/manifest/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/export/manifest/columns';
	import DeleteDialog from '$lib/components/dashboard/export/manifest/delete-dialog.svelte';
	import DetailsDialog from '$lib/components/dashboard/export/manifest/details-dialog.svelte';

	let { data }: { data: any } = $props();

	// --- State ---
	let allItems = $state<Manifest[]>(data.items || []);
	let totalItems = $state(data.total || 0);
	let currentPage = $state(data.page || 1);
	let pageSize = $state(50);
	let loading = $state(false);
	let error = $state<string | null>(data.error || null);

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

	// Filter state
	let filters = $state({
		search: '',
		manifest_number: ''
	});

	// Dialog states
	let showDelete = $state(false);
	let showDetails = $state(false);


	// Pasamos canEdit y canDelete a las columnas por si tu DataTable tiene acciones por fila
	const columns = createColumns();

	// --- Lifecycle ---
	onMount(() => {
		if (browser) {
			const handleCompanyChange = () => reloadData();
			window.addEventListener('companyChanged', handleCompanyChange);
			return () => window.removeEventListener('companyChanged', handleCompanyChange);
		}
	});

	// --- Actions ---
	async function reloadData() {
		if (!companyStore.activeCompany) return;

		loading = true;
		error = null;
		try {
			const response = await manifestApi.list(companyStore.activeCompany.id, {
				...filters,
				skip: '0',
				limit: pageSize.toString()
			});

			if (response.error) {
				toast.error(response.error);
				error = response.error;
				return;
			}

			if (response.data) {
				allItems = response.data.items || [];
				totalItems = response.data.total || 0;
				currentPage = 1;
			}
		} catch (e: any) {
			console.error('Error reloading manifests:', e);
			toast.error('Error al cargar datos');
		} finally {
			loading = false;
		}
	}

	async function loadMore() {
		if (loading || allItems.length >= totalItems) return;

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

			const response = await manifestApi.list(companyId, {
				...filters,
				skip: allItems.length.toString(),
				limit: pageSize.toString()
			});

			if (response.error) {
				toast.error(response.error);
				return;
			}

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

	let filterTimeout: any;
	function handleFilterChange() {
		if (filterTimeout) clearTimeout(filterTimeout);
		filterTimeout = setTimeout(() => {
			reloadData();
		}, 300);
	}

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

<div class="space-y-6 p-6 pb-24">
	<!-- Header -->
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-3xl font-bold tracking-tight">Manifiestos / Entry's</h1>
			<p class="text-muted-foreground">Gestión de manifiestos de exportación</p>
		</div>
		<Button onclick={() => goto('/dashboard/export/manifest/edit')}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Manifiesto
		</Button>
	</div>

	<!-- Filters Card -->
	<Card.Root>
		<Card.Header>
			<Card.Title class="flex items-center gap-2 text-lg">
				<Search class="h-5 w-5 text-muted-foreground" /> Filtros
			</Card.Title>
			<Card.Description>Busca manifiestos por número o descripción</Card.Description>
		</Card.Header>
		<Card.Content>
			<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
				<div class="space-y-2">
					<Label for="filter-num">Número de Manifiesto</Label>
					<Input
						id="filter-num"
						placeholder="Ej: MAN-2024-001"
						bind:value={filters.manifest_number}
						oninput={handleFilterChange}
					/>
				</div>
				<div class="space-y-2">
					<Label for="filter-search">Búsqueda General</Label>
					<Input
						id="filter-search"
						placeholder="Descripción, transportista..."
						bind:value={filters.search}
						oninput={handleFilterChange}
					/>
				</div>
			</div>
		</Card.Content>
	</Card.Root>

	{#if error}
		<Card.Root class="border-destructive">
			<Card.Header>
				<Card.Title class="text-destructive">Error</Card.Title>
				<Card.Description>{error}</Card.Description>
			</Card.Header>
		</Card.Root>
	{/if}

	<!-- List Card -->
	<Card.Root>
		<Card.Header>
			<div class="flex items-center justify-between">
				<div>
					<Card.Title class="text-xl">Listado de Manifiestos</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>
			<DataTable
				data={allItems}
				{columns}
				{loading}
				hasMore={allItems.length < totalItems}
				{loadMore}
				{selectedId}
				onRowClick={handleRowClick}
			/>
		</Card.Content>
	</Card.Root>
</div>

<!-- Sticky Footer Actions -->
<div
	class="fixed right-0 bottom-0 left-0 z-[5] 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-6 py-4">
		<div class="flex items-center justify-between">
			<div class="text-sm text-muted-foreground italic">
				{#if selectedItem}
					Seleccionado: <span class="font-mono font-bold text-foreground"
						>{selectedItem.manifest_number}</span
					>
				{/if}
			</div>
			<div class="flex gap-2">
				<Button
					variant="outline"
					size="sm"
					onclick={() => (showDetails = true)}
					disabled={!selectedItem}
				>
					<FileText class="mr-2 h-4 w-4" />
					Ver Detalles
				</Button>
				<Button
					variant="outline"
					size="sm"
					onclick={() => selectedItem && goto(`/dashboard/export/manifest/edit/${selectedId}`)}
					disabled={!selectedItem}
				>
					Editar
				</Button>
				<Button
					variant="outline"
					size="sm"
					onclick={() => (showDelete = true)}
					disabled={!selectedItem}
					class="text-destructive hover:bg-destructive/5"
				>
					Borrar
				</Button>
			</div>
		</div>
	</div>
</div>

<!-- Dialogs -->
<DeleteDialog bind:open={showDelete} manifest={selectedItem} onSuccess={reloadData} />
<DetailsDialog bind:open={showDetails} manifest={selectedItem} />
