<script lang="ts">
	import { userHasPrevalidatorsAction } from '$lib/permissions/catalogs/prevalidators-permissions';

	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { browser } from '$app/environment';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Pencil, Plus, Trash2 } from 'lucide-svelte';
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/prevalidators/columns';
	import CreateEditDialog from '$lib/components/dashboard/general_catalogs/prevalidators/create-edit-dialog.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaPrevalidadores } from '$lib/config/shortcuts/dashboard/general_catalogs/prevalidators/list';
	import { getPrevalidators, deletePrevalidator, type Prevalidator } from '$lib/api/dashboard/a76/general_catalogs/prevalidators';
	import { companyStore } from '$lib/stores/company.svelte';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	let { data } = $props();
	let dialogOpen = $state(false);
	let editingItem = $state<Prevalidator | null>(null);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);
	let selectedIds = $state<(string | number)[]>([]);

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

	const isError = $derived(!canView || status >= 400 || error);

	// Atajos
	useShortcuts(
		'Lista Prevalidadores',
		obtenerAtajosListaPrevalidadores({
			manejarNuevo: () => {
				if (!canCreate) return;
				editingItem = null;
				dialogOpen = true;
			},
			manejarActualizar: handleSuccess
		})
	);

	let searchCode = $state($page.url.searchParams.get('code') || '');
	let searchDesc = $state($page.url.searchParams.get('description') || '');
	let timeout: ReturnType<typeof setTimeout>;

	let allItems = $state(data.prevalidators?.items || []);
	let currentPage = $state(data.prevalidators?.page || 1);
	let pageSize = $state(data.prevalidators?.page_size || 50);
	let totalItems = $state(data.prevalidators?.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);

	const selectedItem = $derived(
		selectedIds.length === 1 ? allItems.find((item: any) => item.id === selectedIds[0]) ?? null : null
	);

	$effect(() => {
		if (data.prevalidators) {
			allItems = data.prevalidators.items || [];
			currentPage = data.prevalidators.page || 1;
			totalItems = data.prevalidators.total || 0;
			pageSize = data.prevalidators.page_size || pageSize;
		}
	});

	async function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(async () => {
			if (!companyStore.activeCompany) return;
			loading = true;
			error = null;
			try {
				const filters: Record<string, string> = {};
				if (searchCode) filters.code = searchCode;
				if (searchDesc) filters.description = searchDesc;

				const response = await getPrevalidators(1, pageSize, filters, companyStore.activeCompany.id);
				if (response.data?.items) {
					allItems = response.data.items;
					currentPage = response.data.page || 1;
					totalItems = response.data.total || 0;
				}
			} catch (err) {
				error = 'Error aplicando filtros';
				console.error('Error applying filters:', err);
			} finally {
				loading = false;
			}

			const url = new URL($page.url);
			if (searchCode) url.searchParams.set('code', searchCode);
			else url.searchParams.delete('code');

			if (searchDesc) url.searchParams.set('description', searchDesc);
			else url.searchParams.delete('description');

			history.replaceState(history.state, '', url);
		}, 500);
	}

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		error = null;
		try {
			const filters: Record<string, string> = {};
			if (searchCode) filters.code = searchCode;
			if (searchDesc) filters.description = searchDesc;

			const response = await getPrevalidators(
				currentPage + 1,
				pageSize,
				filters,
				companyStore.activeCompany.id
			);
			if (response.data?.items) {
				allItems = [...allItems, ...response.data.items];
				currentPage += 1;
				totalItems = response.data.total || 0;
			}
		} catch (err) {
			error = 'Error cargando mas datos';
			console.error('Error loading more prevalidators:', err);
		} finally {
			loading = false;
		}
	}

	async function reloadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		error = null;
		try {
			const filters: Record<string, string> = {};
			if (searchCode) filters.code = searchCode;
			if (searchDesc) filters.description = searchDesc;

			const response = await getPrevalidators(1, pageSize, filters, companyStore.activeCompany.id);
			if (response.data?.items) {
				allItems = response.data.items;
				currentPage = response.data.page || 1;
				totalItems = response.data.total || 0;
			}
		} catch (err) {
			error = 'Error al recargar datos';
			console.error('Error reloading prevalidators:', err);
		} finally {
			loading = false;
		}
	}

	function handleSuccess() {
		dialogOpen = false;
		editingItem = null;
		selectedIds = [];
		reloadData();
	}

	function handleRowClick(row: Prevalidator) {
		const id = row.id;
		selectedIds = selectedIds.includes(id) ? [] : [id];
	}

	function handleRowDoubleClick(row: Prevalidator) {
		if (!canEdit) return;
		editingItem = row;
		dialogOpen = true;
	}

	function handleEditSelected() {
		if (!selectedItem || !canEdit) return;
		editingItem = selectedItem;
		dialogOpen = true;
	}

	async function handleDeleteSelected() {
		if (!selectedItem || !companyStore.activeCompany || !canDelete) return;

		if (!confirm(`¿Estás seguro de eliminar el prevalidador "${selectedItem.code}"?`)) {
			return;
		}

		loading = true;
		error = null;

		try {
			await deletePrevalidator(selectedItem.id, companyStore.activeCompany.id);

			selectedIds = [];
			await reloadData();
		} catch (err) {
			error = 'Error al eliminar el prevalidador';
			console.error('Error deleting prevalidator:', err);
		} finally {
			loading = false;
		}
	}

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

<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">
	{#if isError}
		<ErrorState 
			status={!canView ? 403 : status} 
			error={!canView ? 'Permission denied: cat_prevalidators.view' : (error || '')} 
			onRetry={reloadData} 
		/>
	{:else}
		<div class="flex items-center justify-between">
			<div>
				<h1 class="text-2xl font-bold tracking-tight">Prevalidadores</h1>
				<p class="text-muted-foreground">Catálogo de prevalidadores</p>
			</div>
			<div class="flex items-center gap-3">
				<Button
					variant="outline"
					size="sm"
					class="h-9"
					onclick={reloadData}
				>
					Actualizar
				</Button>
				{#if canCreate}
					<Button
						class="h-9"
						onclick={() => {
							editingItem = null;
							dialogOpen = true;
						}}
					>
						<Plus class="mr-2 h-4 w-4" />
						Nuevo Prevalidador
					</Button>
				{/if}
			</div>
		</div>

		{#if error}
			<div class="flex-none rounded-md border border-destructive px-4 py-3 text-sm text-destructive">
				{error}
			</div>
		{/if}

		<Card.Root class="border bg-background flex flex-col flex-1 overflow-hidden min-h-0">
			<Card.Header>
				<div class="flex flex-wrap items-center justify-between gap-3">
					<Card.Title>Listado de Prevalidadores</Card.Title>
					<div class="flex flex-wrap items-center gap-2">
						<Input placeholder="Código" bind:value={searchCode} oninput={handleSearch} class="h-9 w-36 bg-card lg:w-44" />
						<Input placeholder="Descripción" bind:value={searchDesc} oninput={handleSearch} class="h-9 w-44 bg-card lg:w-64" />
					</div>
				</div>
			</Card.Header>
			<Card.Content class="p-0 flex-1 overflow-hidden min-h-0">
				<div class="rounded-md border bg-background overflow-hidden h-full">
					<InfiniteDataTable data={allItems} {columns} {loading} {hasMore} {loadMore} />
				</div>
			</Card.Content>
		</Card.Root>

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

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

	<div
		id="prevalidators-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">
				<Button
					variant="outline"
					size="sm"
					onclick={handleEditSelected}
					disabled={selectedIds.length !== 1}
				>
					<Pencil size={16} class="mr-2" />
					Editar
				</Button>
				<Button
					variant="outline"
					size="sm"
					onclick={handleDeleteSelected}
					disabled={selectedIds.length !== 1}
					class="text-destructive hover:bg-destructive/10 hover:text-destructive"
				>
					<Trash2 size={16} class="mr-2" />
					Eliminar
				</Button>
			</div>
		</div>
	</div>

	<CreateEditDialog
		bind:open={dialogOpen}
		item={editingItem}
		onSuccess={handleSuccess}
	/>
</div>
