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

	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import type { Equivalency } from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
	import { createCatalogColumns } from '$lib/components/dashboard/general_catalogs/equivalencies/catalog-columns';
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	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, RefreshCw, Trash2 } from 'lucide-svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaEquivalencias } from '$lib/config/shortcuts/dashboard/general_catalogs/equivalencies/list';
	import DataEquivalenciesDialog from '$lib/components/dashboard/general_catalogs/equivalencies/data-equivalencies-dialog.svelte';
	import type { PageData } from './$types';
	import { getEquivalencies, deleteEquivalency } from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
	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 error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

	let dataDialogOpen = $state(false);
	let selectedEquivalency = $state<Equivalency | null>(null);
	let dataMode = $state<'create' | 'edit'>('edit');
	
	// Filtros
	let searchFrom = $state($page.url.searchParams.get('from_unit_code') || '');
	let timeout: ReturnType<typeof setTimeout>;

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

	let selectedIds = $state<(string | number)[]>([]);
	const singleSelected = $derived(
		selectedIds.length === 1 ? allItems.find((item: Equivalency) => item.id === selectedIds[0]) ?? null : null
	);

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

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

	// Atajos
	useShortcuts(
		'Lista Equivalencias',
		obtenerAtajosListaEquivalencias({
			manejarNuevo: () => {
				selectedEquivalency = null;
				dataMode = 'create';
				dataDialogOpen = true;
			},
			manejarActualizar: () => reloadData()
		})
	);

	$effect(() => {
		if (data.equivalencies) {
			allItems = data.equivalencies.items || [];
			currentPage = data.equivalencies.page || 1;
			totalItems = data.equivalencies.total || 0;
			pageSize = data.equivalencies.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 (searchFrom) filters.from_unit_code = searchFrom;

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

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

			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 (searchFrom) filters.from_unit_code = searchFrom;

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

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

			const response = await getEquivalencies(1, pageSize, companyStore.activeCompany.id, filters);
			const payload = (response.data || response) as any;
			if (payload?.items) {
				allItems = payload.items;
				currentPage = payload.page || 1;
				totalItems = payload.total;
			}
		} catch (err: any) {
			error = err.message || 'Error al recargar datos';
			console.error('Error reloading equivalencies:', err);
			status = err.status || 500;
		} finally {
			loading = false;
		}
	}

	function handleSuccess() {
		dataDialogOpen = false;
		selectedEquivalency = null;
		selectedIds = [];
		reloadData();
	}

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

	function handleRowDoubleClick(row: Equivalency) {
		selectedEquivalency = row;
		dataMode = 'edit';
		dataDialogOpen = true;
	}

	function handleEditSelected() {
		if (!singleSelected) return;
		selectedEquivalency = singleSelected;
		dataMode = 'edit';
		dataDialogOpen = true;
	}

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

		if (!confirm('¿Estás seguro de eliminar la equivalencia seleccionada?')) {
			return;
		}

		loading = true;
		error = null;

		try {
			await deleteEquivalency(singleSelected.id, companyStore.activeCompany.id);
			selectedIds = [];
			await reloadData();
		} catch (err) {
			error = 'Error al eliminar la equivalencia';
			console.error('Error deleting equivalency:', err);
		} finally {
			loading = false;
		}
	}

	function handleOpenInsertItems(row: Equivalency) {
		selectedEquivalency = row;
		dataMode = 'create';
		dataDialogOpen = true;
	}

	function handleOpenEditCatalog(row: Equivalency) {
		selectedEquivalency = row;
		dataMode = 'edit';
		dataDialogOpen = true;
	}

	const columns = $derived(
		createCatalogColumns({
			onInsertItems: handleOpenInsertItems,
			onEdit: handleOpenEditCatalog,
			onSuccess: handleSuccess,
			canEdit,
			canDelete
		})
	);
</script>

<div
	class="flex h-[calc(100svh-4rem)] flex-col gap-6 overflow-hidden p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]"
>
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Equivalencias</h1>
			<p class="text-muted-foreground">Gestión del catálogo de equivalencias de unidades de medida</p>
		</div>
		<div class="flex items-center gap-3">
			<Button variant="outline" size="sm" class="h-9" onclick={() => window.location.reload()}>
				<RefreshCw class="mr-2 h-4 w-4" />
				Actualizar
			</Button>
			{#if !isError && canCreate}
				<Button
					class="h-9"
					onclick={() => {
						dataMode = 'create';
						selectedEquivalency = null;
						dataDialogOpen = true;
					}}
				>
					<Plus class="mr-2 h-4 w-4" />
					Nueva Equivalencia
				</Button>
			{/if}
		</div>

	</div>

	{#if isError}
		<ErrorState
			status={!canView ? 403 : status}
			error={!canView ? 'Permission denied: cat_equivalencies.view' : error || ''}
			onRetry={() => window.location.reload()}
		/>
	{:else}
		{#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="flex min-h-0 flex-1 flex-col overflow-hidden border bg-background">
			<Card.Header>
				<div class="flex flex-wrap items-center justify-between gap-3">
					<Card.Title>Listado de Equivalencias</Card.Title>
					<div class="flex flex-wrap items-center gap-2">
						<Input
							placeholder="Identificador"
							bind:value={searchFrom}
							oninput={handleSearch}
							class="h-9 w-40 bg-card lg:w-52"
						/>
					</div>
				</div>
			</Card.Header>
			<Card.Content class="min-h-0 flex-1 overflow-hidden p-0">
				<div class="flex h-full flex-col overflow-hidden rounded-md border bg-background">
					<InfiniteDataTable
						data={allItems}
						{columns}
						{loading}
						{hasMore}
						{loadMore}
						{selectedIds}
						onSelectedIdsChange={(ids) => (selectedIds = ids)}
						onRowClick={handleRowClick}
						onRowDoubleClick={handleRowDoubleClick}
					/>
				</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="equivalencies-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 !== 1}
							class="text-destructive hover:bg-destructive/10 hover:text-destructive"
						>
							<Trash2 size={16} class="mr-2" />
							Eliminar
						</Button>
					{/if}
				</div>
			</div>
		</div>
	<DataEquivalenciesDialog
		bind:open={dataDialogOpen}
		equivalency={selectedEquivalency}
		mode={dataMode}
		onSuccess={handleSuccess}
	/>
</div>
