<script lang="ts">
	import { Button } from "$lib/components/ui/button";
	import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
	import { pedimentosApi, type Pedimento } from "$lib/api/dashboard/a76/pedimentos";
	import { companyStore } from "$lib/stores/company.svelte";
	import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';

	let {
		item,
		onSuccess
	}: {
		item: Pedimento;
		onSuccess?: () => void;
	} = $props();

	let loading = $state(false);
	let error = $state<string | null>(null);

	async function handleDelete() {
		if (!confirm(`¿Estás seguro de eliminar el pedimento #${item.id}?`)) {
			return;
		}

		loading = true;
		error = null;

		try {
			const companyId = companyStore.activeCompany?.id;
			const response = await pedimentosApi.delete(item.id, companyId);

			if (response.error) {
				if (response.status === 401) {
					error = 'Sesión expirada. Recargando página...';
					setTimeout(() => {
						window.location.reload();
					}, 1500);
				} else {
					error = response.error;
					alert(`Error al eliminar: ${response.error}`);
				}
				return;
			}

			// Éxito
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : "Error al eliminar";
			alert(`Error: ${error}`);
			console.error("Error deleting:", e);
		} finally {
			loading = false;
		}
	}

	function handleEdit() {
		// Navegar a la página de edición
		window.location.href = `/dashboard/pedimentos/edit/${item.id}`;
	}
</script>

<DropdownMenu.Root>
	<DropdownMenu.Trigger>
		{#snippet child({ props })}
			<Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
				<span class="sr-only">Abrir menú</span>
				<EllipsisVertical class="h-4 w-4" />
			</Button>
		{/snippet}
	</DropdownMenu.Trigger>
	<DropdownMenu.Content align="end" class="w-[160px]">
		<DropdownMenu.Label>Acciones</DropdownMenu.Label>
		<DropdownMenu.Separator />
		<DropdownMenu.Item onclick={handleEdit}>
			<Pencil class="mr-2 h-4 w-4" />
			Editar
		</DropdownMenu.Item>
		<DropdownMenu.Separator />
		<DropdownMenu.Item onclick={handleDelete} class="text-destructive" disabled={loading}>
			{#if loading}
				<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
			{:else}
				<Trash2 class="mr-2 h-4 w-4" />
			{/if}
			Eliminar
		</DropdownMenu.Item>
	</DropdownMenu.Content>
</DropdownMenu.Root>
