<script lang="ts">
	import { Button } from "$lib/components/ui/button";
	import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
	import { deleteIdentifier, type Identifier } from "$lib/api/dashboard/a76/general_catalogs/identifiers";
	import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
	import CreateEditDialog from "./create-edit-dialog.svelte";

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

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

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

		loading = true;
		error = null;

		try {
			const response = await deleteIdentifier(item.id);

			if (response.error) {
                error = response.error;
                alert(`Error al eliminar: ${response.error}`);
				return;
			}

			if (onSuccess) onSuccess();
		} catch (e) {
			error = 'Error de conexión';
			console.error(e);
            alert('Error de conexión al eliminar');
		} finally {
			loading = false;
		}
	}
</script>

<DropdownMenu.Root>
	<DropdownMenu.Trigger>
		{#snippet child({ props })}
			<Button {...props} variant="ghost" size="icon" class="h-8 w-8 p-0">
				<span class="sr-only">Abrir menú</span>
				<EllipsisVertical class="h-4 w-4" />
			</Button>
		{/snippet}
	</DropdownMenu.Trigger>
	<DropdownMenu.Content align="end">
		<DropdownMenu.Label>Acciones</DropdownMenu.Label>
		<DropdownMenu.Item onclick={() => dialogOpen = true}>
			<Pencil class="mr-2 h-4 w-4" />
			Editar
		</DropdownMenu.Item>
		<DropdownMenu.Item onclick={handleDelete} class="text-red-600">
			{#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>

<CreateEditDialog 
	bind:open={dialogOpen} 
	mode="edit" 
	{item} 
	{onSuccess} 
/>
