<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/trailers/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/transportation/trailers/columns';

	import { trailersApi, type Trailer } from '$lib/api/dashboard/a76/trailers';
	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 { userHasTrailersAction } from '$lib/permissions/catalogs/trailers-permissions';

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

	// --- ESTADO ---
	let data = $state<Trailer[]>([]);
	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<Trailer | null>(null);
	let selectedIds = $state<(string | number)[]>([]);
	const selectedTrailer = $derived(
		selectedIds.length === 1 ? data.find((t) => t.trailer_number === selectedIds[0]) : null
	);
	const hasSelection = $derived(selectedIds.length > 0);

	// Filtros
	let searchNumber = $state($page.url.searchParams.get('trailer_number') || '');
	let searchPlate = $state($page.url.searchParams.get('plate_number') || '');
	let searchTimeout: NodeJS.Timeout;

	// --- LOGICA ---
	async function loadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await trailersApi.list(companyStore.activeCompany.id, {
				page: 1,
				page_size: pageSize,
				trailer_number: searchNumber,
				plate_number: searchPlate
			});

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

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await trailersApi.list(companyStore.activeCompany.id, {
				page: currentPage + 1,
				page_size: pageSize,
				trailer_number: searchNumber,
				plate_number: searchPlate
			});

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

	function handleDialogSuccess() {
		createDialogOpen = false;
		editingItem = null;
		loadData();
	}

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

	function handleRowClick(row: Trailer) {
		const id = row.trailer_number;
		if (selectedIds.includes(id)) {
			selectedIds = selectedIds.filter((i) => i !== id);
		} else {
			selectedIds = [id];
		}
	}

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

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

		if (!companyStore.activeCompany) return;

		try {
			const response = await trailersApi.delete(
				selectedTrailer.trailer_number,
				companyStore.activeCompany.id
			);
			if (response.error) {
				alert(`❌ Error al eliminar:\n\n${response.error}`);
			} else {
				alert(`✅ Trailer 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 (searchNumber) url.searchParams.set('trailer_number', searchNumber);
			else url.searchParams.delete('trailer_number');

			if (searchPlate) url.searchParams.set('plate_number', searchPlate);
			else url.searchParams.delete('plate_number');

			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('Trailers', [
		...obtenerAtajosCatalogoSimple({
			manejarNuevo: () => {
				if (!userHasTrailersAction(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">Trailers</h1>
			<p class="text-muted-foreground">Gestión del catálogo de trailers de la compañía</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 Trailer</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 Trailers</Card.Title><div class="flex flex-wrap items-center gap-2"><Input placeholder="Número" class="h-9 w-40 bg-card lg:w-52" bind:value={searchNumber} oninput={handleSearch} /><Input placeholder="Placas" class="h-9 w-40 bg-card lg:w-52" bind:value={searchPlate} 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 trailers...</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} getRowId={(row) => row.trailer_number} /></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="trailers-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}
