<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 type { Doda } from '$lib/api/dashboard/a76/general_catalogs/doda';
    import { deleteDoda } from '$lib/api/dashboard/a76/general_catalogs/doda';
    import { companyStore } from '$lib/stores/company.svelte';
    import { goto } from '$app/navigation';
    import { toast } from 'svelte-sonner';

    let {
        item,
        onSuccess,
        canEdit = true,
        canDelete = true,
        dodaListBasePath = '/dashboard/despacho/doda'
    }: {
        item: Doda;
        onSuccess?: () => void;
        canEdit?: boolean;
        canDelete?: boolean;
        /** Ruta base donde vive la lista+formulario de DODA (canónica en Despacho). */
        dodaListBasePath?: string;
    } = $props();

    let loading = $state(false);

    async function handleDelete() {
        if (!confirm('¿Está seguro de eliminar este registro DODA?')) {
            return;
        }

        const companyId = companyStore.activeCompany?.id;
        if (!companyId) {
            toast.error('Selecciona una compañía');
            return;
        }

        loading = true;

        try {
            await deleteDoda(item.id, companyId);
            toast.success('DODA eliminado correctamente');
            if (onSuccess) onSuccess();
        } catch (err: unknown) {
            const msg = err instanceof Error ? err.message : 'Error al eliminar DODA';
            toast.error(msg);
        } 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>
        {#if canEdit}
            <DropdownMenu.Item onclick={() => goto(`${dodaListBasePath}?doda_id=${item.id}`)}>
                <Pencil class="mr-2 h-4 w-4" />
                Editar
            </DropdownMenu.Item>
        {/if}
        {#if canDelete}
            <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>
        {/if}
    </DropdownMenu.Content>
</DropdownMenu.Root>

