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

	let {
		item,
		onInsertItems,
		onEdit,
		onSuccess,
		canEdit = true,
		canDelete = true
	}: {
		item: Equivalency;
		onInsertItems: (equivalency: Equivalency) => void;
		onEdit: (equivalency: Equivalency) => void;
		onSuccess?: () => void;
		canEdit?: boolean;
		canDelete?: boolean;
	} = $props();

	let loading = $state(false);

	async function handleDelete() {
		if (!confirm('¿Está seguro de eliminar esta equivalencia?')) return;

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		loading = true;
		try {
			const response = await deleteEquivalency(item.id, companyId);
			if (response.error) throw new Error(response.error);
			onSuccess?.();
		} catch (err: any) {
			console.error('Error deleting equivalency:', err);
			alert(err?.message || 'Error al eliminar la equivalencia');
		} 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={() => onInsertItems(item)}>
			<span>Insertar items</span>
		</DropdownMenu.Item>
		{#if canEdit}
			<DropdownMenu.Item onclick={() => onEdit(item)}>
				<Pencil class="mr-2 h-4 w-4" />
				Editar
			</DropdownMenu.Item>
		{/if}
		{#if canDelete}
			<DropdownMenu.Item onclick={handleDelete} class="text-red-600" disabled={loading}>
				{#if loading}
					<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
				{:else}
					<Trash2 class="mr-2 h-4 w-4" />
				{/if}
				Borrar
			</DropdownMenu.Item>
		{/if}
	</DropdownMenu.Content>
</DropdownMenu.Root>

