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

	import { vehiclesApi, type Vehicle } from '$lib/api/dashboard/a76/vehicles';
	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 { tv } from '$lib/i18n/vehicles';
	import { get } from 'svelte/store';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import { userHasVehiclesAction } from '$lib/permissions/catalogs/vehicles-permissions';

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

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

	// Filtros
	let searchKey = $state($page.url.searchParams.get('vehicle_key') || '');
	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 vehiclesApi.list(companyStore.activeCompany.id, {
				page: 1,
				page_size: pageSize,
				vehicle_key: searchKey,
				plate_number: searchPlate
			});

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

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await vehiclesApi.list(companyStore.activeCompany.id, {
				page: currentPage + 1,
				page_size: pageSize,
				vehicle_key: searchKey,
				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 vehicles:', error);
		} finally {
			loading = false;
		}
	}

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

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

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

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

	async function handleDeleteSelected() {
		if (!selectedVehicle) return;
		if (
			!confirm(
				tv('delete_confirm', { key: selectedVehicle.vehicle_key })
			)
		) {
			return;
		}

		if (!companyStore.activeCompany) return;

		try {
			const response = await vehiclesApi.delete(
				selectedVehicle.vehicle_key,
				companyStore.activeCompany.id
			);
			if (response.error) {
				alert(`${tv('delete_error_title')}\n\n${response.error}`);
			} else {
				alert(tv('delete_success'));
				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('vehicle_key', searchKey);
			else url.searchParams.delete('vehicle_key');

			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(tv('shortcuts_scope'), [
		...obtenerAtajosCatalogoSimple({
			manejarNuevo: () => {
				if (!userHasVehiclesAction(get(currentUser), 'create')) return;
				editingItem = null;
				createDialogOpen = true;
			},
			manejarActualizar: loadData
		}),
		{
			key: 'Ctrl+S',
			description: tv('shortcuts_save'),
			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">{tv('page_title')}</h1>
			<p class="text-muted-foreground">
				{tv('page_subtitle')}
			</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" />{tv('new_vehicle')}</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>{tv('vehicle_list')}</Card.Title><div class="flex flex-wrap items-center gap-2"><Input placeholder={tv('search_key')} class="h-9 w-40 bg-card lg:w-52" bind:value={searchKey} oninput={handleSearch} /><Input placeholder={tv('search_plate')} 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">{tv('loading_vehicles')}</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.vehicle_key} /></div>{/if}</Card.Content>
	</Card.Root>

	<div class="flex-none text-sm text-muted-foreground">{tv('showing_records', { shown: data.length, total: totalItems })}</div>

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

	{#if canEdit || canDelete}
		<div
			id="vehicles-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" />
							{tv('edit')}
						</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" />
							{tv('delete')}
						</Button>
					{/if}
				</div>
			</div>
		</div>
	{/if}

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