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

    let {
        item,
        onSuccess,
        canEdit = true,
        canDelete = true
    }: {
        item: INPC;
        onSuccess?: () => void;
        canEdit?: boolean;
        canDelete?: boolean;
    } = $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 este registro de INPC (${item.year}/${item.month})?`)) {
            return;
        }

        if (!companyStore.activeCompany) {
            return;
        }

        loading = true;
        error = null;

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

            if (response.error) {
                return;
            }

            // Éxito
            if (response.status === 204 || response.status === 200 || !response.error) {
                if (onSuccess) {
                    onSuccess();
                }
            }
        } catch (e) {
            const errorMsg = e instanceof Error ? e.message : 'Error desconocido al eliminar el registro';
            console.error('Error deleting INPC:', errorMsg);
        } 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={() => dialogOpen = true}> 
                <Pencil class="mr-2 h-4 w-4" />
                Editar
            </DropdownMenu.Item>
        {/if}
        {#if canDelete}
            {#if canEdit}
                <DropdownMenu.Separator />
            {/if}
            <DropdownMenu.Item class="text-destructive focus:text-destructive" onclick={handleDelete} 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>
        {/if}
        {#if !canEdit && !canDelete}
            <DropdownMenu.Item disabled>Sin permisos</DropdownMenu.Item>
        {/if}
    </DropdownMenu.Content>
</DropdownMenu.Root>

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