<script lang="ts">
	import { userHasMultiCurrencyTypesAction } from '$lib/permissions/catalogs/multi-currency-types-permissions';

	import { page } from '$app/stores';
	import type { ColumnDef } from '@tanstack/table-core';
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	import CreateDialog from '$lib/components/dashboard/general_catalogs/multi_currency_types/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 { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaMonedas } from '$lib/config/shortcuts/dashboard/general_catalogs/multi_currency_types/list';
	import {
		getMultiCurrencyTypes,
		deleteMultiCurrencyType,
		type MultiCurrencyType
	} from '$lib/api/dashboard/a76/general_catalogs/multi-currency-types';
	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<MultiCurrencyType | null>(null);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

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

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

	// Atajos
	useShortcuts(
		'Lista Monedas',
		obtenerAtajosListaMonedas({
			manejarNuevo: () => {
				editingItem = null;
				dialogOpen = true;
			},
			manejarActualizar: handleSuccess
		})
	);

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

	const columns: ColumnDef<MultiCurrencyType>[] = [
		{
			accessorKey: 'currency_type_code',
			header: 'Código Moneda',
			cell: ({ row }) => row.original.currency_type_code || '-'
		},
		{
			accessorKey: 'country_key',
			header: 'País',
			cell: ({ row }) => row.original.country_key || '-'
		},
		{
			accessorKey: 'conversion_factor',
			header: 'Factor Conversión',
			cell: ({ row }) => row.original.conversion_factor ?? '-'
		},
		{
			accessorKey: 'publication_date',
			header: 'Fecha Publicación',
			cell: ({ row }) => row.original.publication_date || '-'
		}
	];

	let allItems = $state<MultiCurrencyType[]>(data.types?.items || []);
	let currentPage = $state(data.types?.page || 1);
	let pageSize = $state(data.types?.page_size || 50);
	let totalItems = $state(data.types?.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.types) {
			allItems = data.types.items || [];
			currentPage = data.types.page || 1;
			totalItems = data.types.total || 0;
			pageSize = data.types.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 getMultiCurrencyTypes(
					companyStore.activeCompany.id,
					1,
					pageSize,
					{
						currency_type_code: searchCode || undefined,
						country_key: searchCountry || undefined
					}
				);
				if (response.error) {
					throw new Error(response.error);
				}
				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('currency_type_code', searchCode);
			else url.searchParams.delete('currency_type_code');

			if (searchCountry) url.searchParams.set('country_key', searchCountry);
			else url.searchParams.delete('country_key');

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

	async function loadMore() {
		if (loading || !hasMore || !companyStore.activeCompany) return;
		loading = true;
		error = null;
		try {
			const response = await getMultiCurrencyTypes(
				companyStore.activeCompany.id,
				currentPage + 1,
				pageSize,
				{
					currency_type_code: searchCode || undefined,
					country_key: searchCountry || undefined
				}
			);
			if (response.error) {
				throw new Error(response.error);
			}
			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 multi-currency types:', err);
		} finally {
			loading = false;
		}
	}

	async function reloadData() {
		if (!companyStore.activeCompany) return;
		loading = true;
		error = null;
		try {
			const response = await getMultiCurrencyTypes(
				companyStore.activeCompany.id,
				1,
				pageSize,
				{
					currency_type_code: searchCode || undefined,
					country_key: searchCountry || undefined
				}
			);
			if (response.error) {
				throw new Error(response.error);
			}
			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 multi-currency types:', err);
		} finally {
			loading = false;
		}
	}

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

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

	function handleRowDoubleClick(row: MultiCurrencyType) {
		editingItem = row;
		dialogOpen = true;
	}

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

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

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

		loading = true;
		error = null;

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

			selectedIds = [];
			await reloadData();
		} catch (err) {
			error = 'Error al eliminar el tipo de moneda';
			console.error('Error deleting multi-currency type:', 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">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Tipos de Moneda Múltiple</h1>
			<p class="text-muted-foreground">Gestión del catálogo de tipos de moneda múltiple</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 !isError && canCreate}
				<Button
					class="h-9"
					onclick={() => {
						editingItem = null;
						dialogOpen = true;
					}}
				>
					<Plus class="mr-2 h-4 w-4" />
					Nuevo Tipo
				</Button>
			{/if}
		</div>
	</div>

	{#if isError}
		<ErrorState 
			status={!canView ? 403 : status} 
			error={!canView ? 'Permission denied: cat_multi_currency_types.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 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 Monedas</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="País"
							bind:value={searchCountry}
							oninput={handleSearch}
							class="h-9 w-36 bg-card lg:w-44"
						/>
					</div>
				</div>
			</Card.Header>
			<Card.Content class="min-h-0 flex-1 overflow-hidden p-0">
				<div class="h-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>

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

		<div
			id="multi-currency-types-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>

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