<script lang="ts">
	import { userHasUmGeneralAction } from '$lib/permissions/catalogs/um-general-permissions';

	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/units_of_measure/general/columns';
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/general_catalogs/units_of_measure/general/create-edit-dialog.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 { obtenerAtajosListaUnidadesGeneral } from '$lib/config/shortcuts/dashboard/general_catalogs/units_of_measure/general/list';
	import { getUnitsOfMeasureGeneral, deleteUnitOfMeasureGeneral, type UnitOfMeasureGeneral } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
	import { companyStore } from '$lib/stores/company.svelte';
	import type { PageData } from './$types';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	let { data }: { data: PageData } = $props();

	let createDialogOpen = $state(false);
	let editingItem = $state<UnitOfMeasureGeneral | null>(null);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

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

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

	// Atajos
	useShortcuts(
		'Lista Unidades de Medida',
		obtenerAtajosListaUnidadesGeneral({
			manejarNuevo: () => {
				editingItem = null;
				createDialogOpen = true;
			},
			manejarActualizar: handleSuccess
		})
	);

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

	let allItems = $state<UnitOfMeasureGeneral[]>(data.general_units?.items || []);
	let currentPage = $state(data.general_units?.page || 1);
	let pageSize = $state(data.general_units?.page_size || 50);
	let totalItems = $state(data.general_units?.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);
	let selectedIds = $state<(string | number)[]>([]);
	const selectedItem = $derived(
		selectedIds.length === 1
			? allItems.find((item) => String(item.id) === String(selectedIds[0])) ?? null
			: null
	);

	$effect(() => {
		if (data.general_units) {
			allItems = data.general_units.items || [];
			currentPage = data.general_units.page || 1;
			totalItems = data.general_units.total || 0;
			pageSize = data.general_units.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 getUnitsOfMeasureGeneral(
					1,
					pageSize,
					companyStore.activeCompany.id,
					filters
				);
				if (response.error) {
					throw new Error(response.error);
				}
				if (response.data) {
					allItems = response.data.items;
					currentPage = 1;
					totalItems = response.data.total;
				}
			} 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 getUnitsOfMeasureGeneral(
				currentPage + 1,
				pageSize,
				companyStore.activeCompany.id,
				filters
			);
			if (response.error) {
				throw new Error(response.error);
			}
			if (response.data?.items) {
				allItems = [...allItems, ...response.data.items];
				currentPage += 1;
				totalItems = response.data.total;
			}
		} catch (err) {
			error = 'Error cargando mas datos';
			console.error('Error loading more general units:', 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 getUnitsOfMeasureGeneral(
				1,
				pageSize,
				companyStore.activeCompany.id,
				filters
			);
			if (response.error) {
				throw new Error(response.error);
			}
			if (response.data) {
				allItems = response.data.items;
				currentPage = 1;
				totalItems = response.data.total;
			}
		} catch (err) {
			error = 'Error al recargar datos';
			console.error('Error reloading general units:', err);
		} finally {
			loading = false;
		}
	}

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

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

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

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

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

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

		loading = true;
		error = null;

		try {
			const response = await deleteUnitOfMeasureGeneral(selectedItem.id, companyStore.activeCompany.id);
			if (response.error) {
				throw new Error(response.error);
			}

			selectedIds = [];
			await reloadData();
		} catch (err) {
			error = 'Error al eliminar la unidad';
			console.error('Error deleting general unit:', 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_um_general.view' : (error || '')} 
			onRetry={reloadData} 
		/>
	{:else}
		<div class="flex items-center justify-between">
			<div>
				<h1 class="text-2xl font-bold tracking-tight">Unidades de Medida</h1>
				<p class="text-muted-foreground">Catálogo general de unidades de medida</p>
			</div>
			<div class="flex items-center gap-3">
				<Button variant="outline" size="sm" class="h-9" onclick={reloadData}>
					<RefreshCw class="mr-2 h-4 w-4" />
					Actualizar
				</Button>
				{#if canCreate}
					<Button
						class="h-9"
						onclick={() => {
							editingItem = null;
							createDialogOpen = true;
						}}
					>
						<Plus class="mr-2 h-4 w-4" />
						Nueva Unidad
					</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 overflow-hidden">
			<Card.Header>
				<div class="flex flex-wrap items-center justify-between gap-3">
					<Card.Title>Listado de Unidades</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 overflow-hidden">
				<div class="rounded-md border bg-background overflow-hidden">
					<InfiniteDataTable
						{columns}
						data={allItems}
						{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>

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

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

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