<script lang="ts">
	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';

	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/transportation/drivers/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/transportation/drivers/columns';

	import { driversApi, type Driver } from '$lib/api/dashboard/a76/drivers';
	import { companyStore } from '$lib/stores/company.svelte';
	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 { userHasDriversAction } from '$lib/permissions/catalogs/drivers-permissions';

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

	let data = $state<Driver[]>([]);
	let totalItems = $state(0);
	let loading = $state(false);
	let currentPage = $state(1);
	let pageSize = $state(50);
	let createDialogOpen = $state(false);
	let editingItem = $state<Driver | null>(null);
	let selectedIds = $state<(string | number)[]>([]);
	const selectedDriver = $derived(
		selectedIds.length === 1 ? data.find((d) => (d.transporter_key + '-' + d.line) === selectedIds[0]) : null
	);
	const hasSelection = $derived(selectedIds.length > 0);

	let searchTransporterKey = $state('');
	let searchDriverName = $state('');

	let filteredData = $derived(
		data.filter((d) => {
			const tk = searchTransporterKey.trim().toLowerCase();
			const dn = searchDriverName.trim().toLowerCase();
			if (tk && !(d.transporter_key ?? '').toLowerCase().includes(tk)) return false;
			if (dn && !(d.driver_name ?? '').toLowerCase().includes(dn)) return false;
			return true;
		})
	);

	let hasMore = $derived(data.length < totalItems);

	async function loadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await driversApi.list(companyStore.activeCompany.id, {
				page: 1,
				page_size: pageSize
			});
			if (response.data) {
				data = response.data.items;
				currentPage = 1;
				totalItems = response.data.total;
			}
		} catch (error) {
			console.error('Error loading drivers:', error);
		} finally {
			loading = false;
		}
	}

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		try {
			const response = await driversApi.list(companyStore.activeCompany.id, {
				page: currentPage + 1,
				page_size: pageSize
			});
			if (response.data?.items) {
				data = [...data, ...response.data.items];
				currentPage += 1;
				totalItems = response.data.total;
			}
		} catch (error) {
			console.error('Error loading more drivers:', error);
		} finally {
			loading = false;
		}
	}

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

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

	function handleRowClick(row: Driver) {
		const id = row.transporter_key + '-' + row.line;
		if (selectedIds.includes(id)) {
			selectedIds = selectedIds.filter((i) => i !== id);
		} else {
			selectedIds = [id];
		}
	}

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

	async function handleDeleteSelected() {
		if (!selectedDriver) return;
		if (
			!confirm(
				`¿Estás seguro de eliminar el conductor "${selectedDriver.driver_name || selectedDriver.transporter_key + '-' + selectedDriver.line}"?\n\nNota: No se puede eliminar si tiene registros relacionados.`
			)
		) {
			return;
		}

		if (!companyStore.activeCompany) return;

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

	$effect(() => {
		const _c = companyStore.activeCompany?.id;
		loadData();
		
		if (!createDialogOpen) {
			editingItem = null;
		}
	});

	useShortcuts('Conductores', [
		...obtenerAtajosCatalogoSimple({
			manejarNuevo: () => {
				if (!userHasDriversAction(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">Conductores</h1>
			<p class="text-muted-foreground">Gestión del catálogo de conductores</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 Conductor</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 Conductores</Card.Title><div class="flex flex-wrap items-center gap-2"><Input placeholder="Clave transportista" class="h-9 w-44 bg-card lg:w-56" bind:value={searchTransporterKey} /><Input placeholder="Nombre" class="h-9 w-44 bg-card lg:w-56" bind:value={searchDriverName} /></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 conductores...</div>{:else}<div class="rounded-md border bg-background overflow-hidden"><InfiniteDataTable data={filteredData} {columns} {loading} {hasMore} {loadMore} {selectedIds} onSelectedIdsChange={(ids) => (selectedIds = ids)} onRowClick={handleRowClick} onRowDoubleClick={handleRowDoubleClick} getRowId={(row) => row.transporter_key + '-' + row.line} /></div>{/if}</Card.Content>
	</Card.Root>

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

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

	{#if canEdit || canDelete}
		<div
			id="drivers-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}
