<script lang="ts">
	import { userHasExchangeRatesAction } from '$lib/permissions/catalogs/exchange-rates-permissions';

	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import { createColumns } from '$lib/components/dashboard/exchange_rate/columns';
	import CreateEditDialog from '$lib/components/dashboard/exchange_rate/create-edit-dialog.svelte';
	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, Search, Globe } from 'lucide-svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaTiposCambio } from '$lib/config/shortcuts/dashboard/general_catalogs/exchange_rate/list';
	import type { PageData } from './$types';
	import { getExchangeRates, deleteExchangeRate, type ExchangeRate } from '$lib/api/dashboard/a76/general_catalogs/exchange-rate';
	import { companyStore } from '$lib/stores/company.svelte';
	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<ExchangeRate | null>(null);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

	// Filtros
	let searchCurrency = $state($page.url.searchParams.get('local_currency') || '');
	let timeout: ReturnType<typeof setTimeout>;

	let allItems = $state(data.exchange_rates?.items || []);
	let currentPage = $state(data.exchange_rates?.page || 1);
	let pageSize = $state(data.exchange_rates?.page_size || 50);
	let totalItems = $state(data.exchange_rates?.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: ExchangeRate) => item.id === selectedIds[0]) ?? null : null
	);

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

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

	// Atajos
	useShortcuts(
		'Lista Tipos de Cambio',
		obtenerAtajosListaTiposCambio({
			manejarNuevo: () => {
				editingItem = null;
				createDialogOpen = true;
			},
			manejarActualizar: handleSuccess
		})
	);



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

	async function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(async () => {
			if (!companyStore.activeCompany) return;
			loading = true;
			error = null;
			try {
				const response = await getExchangeRates(companyStore.activeCompany.id, {
					local_currency: searchCurrency || undefined,
					page: 1,
					page_size: pageSize
				});
				if (response.data) {
					const payload = (response.data as any).data || response.data;
					allItems = payload.items || [];
					currentPage = payload.page || 1;
					totalItems = payload.total || 0;
				}
			} catch (err) {
				error = 'Error aplicando filtros';
				console.error('Error applying filters:', err);
			} finally {
				loading = false;
			}

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

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

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		error = null;
		try {
			const response = await getExchangeRates(companyStore.activeCompany.id, {
				local_currency: searchCurrency || undefined,
				page: currentPage + 1,
				page_size: pageSize
			});
			const payload = (response.data as any).data || response.data;
			if (payload?.items) {
				allItems = [...allItems, ...payload.items];
				currentPage += 1;
				totalItems = (payload as any).total || 0;
			}
		} catch (err) {
			error = 'Error cargando mas datos';
			console.error('Error loading more exchange rates:', err);
		} finally {
			loading = false;
		}
	}

	async function reloadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		error = null;
		try {
			const response = await getExchangeRates(companyStore.activeCompany.id, {
				local_currency: searchCurrency || undefined,
				page: 1,
				page_size: pageSize
			});
			if (response.data) {
				const payload = (response.data as any).data || response.data;
				allItems = payload.items;
				currentPage = payload.page || 1;
				totalItems = (payload as any).total || 0;
			}
		} catch (err) {
			error = 'Error al recargar datos';
			console.error('Error reloading exchange rates:', err);
		} finally {
			loading = false;
		}
	}

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

	function fetchDOF() {
		// Implementación pendiente
	}

	const columns = $derived(createColumns(handleSuccess, { canEdit, canDelete }));
	function handleRowClick(row: ExchangeRate) {
		const id = row.id;
		selectedIds = selectedIds.includes(id) ? [] : [id];
	}

	function handleRowDoubleClick(row: ExchangeRate) {
		editingItem = row;
		createDialogOpen = true;
	}

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

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

		if (!confirm(`¿Estás seguro de eliminar este tipo de cambio?`)) {
			return;
		}

		loading = true;
		error = null;

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

			selectedIds = [];
			await reloadData();
		} catch (err) {
			error = 'Error al eliminar el tipo de cambio';
			console.error('Error deleting exchange rate:', err);
		} finally {
			loading = false;
		}
	}

</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">
	<div class="flex items-center justify-between gap-4">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Tipos de Cambio</h1>
			<p class="text-muted-foreground">Gestión del catálogo de tipos de cambio oficiales y personalizados</p>
		</div>
		<div class="flex items-center gap-3">
			<Button variant="outline" size="sm" class="h-9" onclick={fetchDOF}>
				<Globe class="mr-2 h-4 w-4" />
				Consultar DOF
			</Button>
			<Button variant="outline" size="sm" class="h-9" onclick={reloadData}>
				<RefreshCw class="mr-2 h-4 w-4" />
				Actualizar
			</Button>
			{#if !isError && canCreate}
				<Button class="h-9" onclick={() => (createDialogOpen = true)}>
					<Plus class="mr-2 h-4 w-4" />
					Nuevo Registro
				</Button>
			{/if}
		</div>

	</div>

	{#if isError}
		<ErrorState 
			status={!canView ? 403 : status} 
			error={!canView ? 'Permission denied: cat_exchange_rates.view' : (error || '')} 
			onRetry={reloadData} 
		/>
	{: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 flex-1 flex-col overflow-hidden border bg-background shadow-sm min-h-0">
			<Card.Header class="px-6 py-4">
				<div class="flex items-center justify-between">
					<Card.Title class="text-lg font-semibold text-foreground/90"
						>Historial de Tipos de Cambio</Card.Title
					>
				</div>
			</Card.Header>
			<Card.Content class="p-0 flex-1 overflow-hidden min-h-0">
				<div class="h-full w-full 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="exchange-rate-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>

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