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


    let {
        item,
        onSuccess,
        canEdit = true,
        canDelete = true
    }: {
        item: Legend;
        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 la leyenda "${item.code}"?\n\nNota: No se puede eliminar si tiene registros relacionados.`)) {
            return;
        }

        if (!companyStore.activeCompany) {
            return;
        }

        loading = true;
        error = null;

        try {
            const response = await deleteLegend(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';
        } 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}
            <DropdownMenu.Separator />
            <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}
    </DropdownMenu.Content>
</DropdownMenu.Root>

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