<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Plus, RefreshCw, Pencil, Trash2 } from 'lucide-svelte';

	// Importar componentes de la librería
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/transportation/transporters/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/transportation/transporters/transporter-columns';

	import { transportersApi, type Transporter } from '$lib/api/dashboard/a76/transporters';
	import { companyStore } from '$lib/stores/company.svelte';
	import { browser } from '$app/environment';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosCatalogoSimple } from '$lib/config/shortcuts/dashboard/general_catalogs/common/factory';
	import { get } from 'svelte/store';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import { userHasTransportersAction } from '$lib/permissions/catalogs/transporters-permissions';

	const canView = $derived(userHasTransportersAction($currentUser, 'view'));
	const canCreate = $derived(userHasTransportersAction($currentUser, 'create'));
	const canEdit = $derived(userHasTransportersAction($currentUser, 'edit'));
	const canDelete = $derived(userHasTransportersAction($currentUser, 'delete'));

	// --- ESTADO ---
	let data = $state<Transporter[]>([]);
	let totalItems = $state(0);
	let loading = $state(false);
	let currentPage = $state(1);
	let pageSize = $state(50);
	let hasMore = $derived(data.length < totalItems);
	let createDialogOpen = $state(false);
	let editingItem = $state<Transporter | null>(null);
	let selectedIds = $state<(string | number)[]>([]);
	const selectedTransporter = $derived(
		selectedIds.length === 1 ? data.find((t) => t.transporter_key === selectedIds[0]) : null
	);
	const hasSelection = $derived(selectedIds.length > 0);

	// Filtros
	let searchKey = $state($page.url.searchParams.get('transporter_key') || '');
	let searchName = $state($page.url.searchParams.get('name') || '');
	let searchTimeout: NodeJS.Timeout;

	// --- LOGICA ---
	async function loadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await transportersApi.list(companyStore.activeCompany.id, {
				page: 1,
				page_size: pageSize,
				transporter_key: searchKey,
				name: searchName
			});

			if (response.data) {
				data = response.data.items;
				currentPage = 1;
				totalItems = response.data.total;
			}
		} catch (error) {
			console.error('Error loading transporters:', error);
		} finally {
			loading = false;
		}
	}

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await transportersApi.list(companyStore.activeCompany.id, {
				page: currentPage + 1,
				page_size: pageSize,
				transporter_key: searchKey,
				name: searchName
			});

			if (response.data?.items) {
				data = [...data, ...response.data.items];
				currentPage += 1;
				totalItems = response.data.total;
			}
		} catch (error) {
			console.error('Error loading more transporters:', error);
		} finally {
			loading = false;
		}
	}
	
	function handleDialogSuccess() {
		createDialogOpen = false;
		editingItem = null;
		loadData();
	}

	function handleRowDoubleClick(row: Transporter) {
		if (!userHasTransportersAction(get(currentUser), 'edit')) return;
		editingItem = row;
		createDialogOpen = true;
	}

	function handleRowClick(row: Transporter) {
		const id = row.transporter_key;
		if (selectedIds.includes(id)) {
			selectedIds = selectedIds.filter((i) => i !== id);
		} else {
			selectedIds = [id]; // Por ahora selección única para simplificar
		}
	}

	function handleEditSelected() {
		if (selectedTransporter) {
			editingItem = selectedTransporter;
			createDialogOpen = true;
		}
	}

	async function handleDeleteSelected() {
		if (!selectedTransporter) return;
		if (
			!confirm(
				`¿Estás seguro de eliminar el transportista "${selectedTransporter.transporter_key}"?\n\nNota: No se puede eliminar si tiene registros relacionados.`
			)
		) {
			return;
		}

		if (!companyStore.activeCompany) return;

		try {
			const response = await transportersApi.delete(
				selectedTransporter.transporter_key,
				companyStore.activeCompany.id
			);
			if (response.error) {
				alert(`❌ Error al eliminar:\n\n${response.error}`);
			} else {
				alert(`✅ Transportista eliminado correctamente`);
				selectedIds = [];
				loadData();
			}
		} catch (e) {
			console.error('Error deleting:', e);
		}
	}

	function handleSearch() {
		if (!browser) return;
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			const url = new URL($page.url);

			if (searchKey) url.searchParams.set('transporter_key', searchKey);
			else url.searchParams.delete('transporter_key');

			if (searchName) url.searchParams.set('name', searchName);
			else url.searchParams.delete('name');

			goto(url, { keepFocus: true, noScroll: true });
		}, 500);
	}

	// Recargar datos cuando cambia el contexto de compañía o la página/filtros
	$effect(() => {
		const _ = { p: $page.url.href, c: companyStore.activeCompany?.id };
		loadData();
		
		if (!createDialogOpen) {
			editingItem = null;
		}
	});

	useShortcuts('Transportistas', [
		...obtenerAtajosCatalogoSimple({
			manejarNuevo: () => {
				if (!userHasTransportersAction(get(currentUser), 'create')) return;
				editingItem = null;
				createDialogOpen = true;
			},
			manejarActualizar: loadData
		}),
		{
			key: 'Ctrl+S',
			description: 'Guardar',
			action: () => {
				if (!createDialogOpen) return;
				document.dispatchEvent(new CustomEvent('save-form'));
			}
		}
	]);

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

{#if !canView}
	<ErrorState status={403} />
{: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">
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Transportistas</h1>
			<p class="text-muted-foreground">Gestión del catálogo de líneas transportistas</p>
		</div>
		<div class="flex items-center gap-3">
			{#if canCreate}
				<Button class="h-9" onclick={() => { editingItem = null; createDialogOpen = true; }}><Plus class="mr-2 h-4 w-4" />Nuevo Transportista</Button>
			{/if}
		</div>
	</div>

	<Card.Root class="border bg-background flex flex-col">
		<Card.Header><div class="flex flex-wrap items-center justify-between gap-3"><Card.Title>Listado de Transportistas</Card.Title><div class="flex flex-wrap items-center gap-2"><Input placeholder="Clave" class="h-9 w-40 bg-card lg:w-52" bind:value={searchKey} oninput={handleSearch} /><Input placeholder="Nombre" class="h-9 w-44 bg-card lg:w-56" bind:value={searchName} oninput={handleSearch} /></div></div></Card.Header>
		<Card.Content class="p-0">{#if loading && data.length === 0}<div class="flex h-64 items-center justify-center text-muted-foreground">Cargando transportistas...</div>{:else}<div class="rounded-md border bg-background overflow-hidden"><InfiniteDataTable {data} {columns} {loading} {hasMore} {loadMore} {selectedIds} onSelectedIdsChange={(ids) => (selectedIds = ids)} onRowClick={handleRowClick} onRowDoubleClick={handleRowDoubleClick} /></div>{/if}</Card.Content>
	</Card.Root>

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

	<div class="h-20"></div>

	{#if canEdit || canDelete}
		<div
			id="transporters-list-footer"
			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 justify-end gap-2">
					{#if canEdit}
						<Button
							variant="outline"
							size="sm"
							onclick={handleEditSelected}
							disabled={selectedIds.length !== 1}
						>
							<Pencil size={16} class="mr-2" />
							Editar
						</Button>
					{/if}
					{#if canDelete}
						<Button
							variant="outline"
							size="sm"
							onclick={handleDeleteSelected}
							disabled={selectedIds.length === 0}
							class="text-destructive hover:bg-destructive/10 hover:text-destructive"
						>
							<Trash2 size={16} class="mr-2" />
							Eliminar
						</Button>
					{/if}
				</div>
			</div>
		</div>
	{/if}

	<CreateEditDialog bind:open={createDialogOpen} item={editingItem} onSuccess={handleDialogSuccess} />
</div>
{/if}
