<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 { ElectronicNotice } from '$lib/api/dashboard/a76/general_catalogs/electronic-notices';
    import { deleteElectronicNotice } from '$lib/api/dashboard/a76/general_catalogs/electronic-notices';
    import { companyStore } from '$lib/stores/company.svelte';
    import CreateEditDialog from './create-edit-dialog.svelte';

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

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

    async function handleDelete() {
        if (!confirm('¿Está seguro de eliminar este aviso electrónico?')) {
            return;
        }

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

        loading = true;

        try {
            await deleteElectronicNotice(item.id, companyId);
            if (onSuccess) onSuccess();
        } catch (err: any) {
            error = err.message || 'Error al eliminar el aviso electrónico';
            console.error('Error deleting electronic notice:', err);
        } finally {
            loading = false;
        }
    }

    function handleEdit() {
        selectedItem = item;
        dialogOpen = true;
    }
</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={handleEdit}>
                <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>

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