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

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

    let loading = $state(false);
    let dialogOpen = $state(false);

    async function handleDelete() {
        if (!confirm(`¿Estás seguro de eliminar la conversión "${conversion.from_unit_code} → ${conversion.to_unit_code}"?\n\nNota: No se puede eliminar si tiene registros relacionados.`)) {
            return;
        }

        if (!companyStore.activeCompany) {
            toast.error('Selecciona una compañía', {
                description: 'No se puede eliminar sin una compañía activa.'
            });
            return;
        }

        loading = true;

        try {
            await deleteUnitConversion(conversion.id, companyStore.activeCompany.id);
            toast.success('Conversión eliminada');
            if (onSuccess) {
                onSuccess(conversion, true);
            }
        } catch (e) {
            const errorMsg = e instanceof Error ? e.message : 'Error desconocido al eliminar el registro';
            toast.error('No se pudo eliminar', { description: 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}
            <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>

<CreateEditDialog
    bind:open={dialogOpen}
    conversion={conversion}
    mode="edit"
    onSuccess={(saved) => onSuccess?.(saved)}
/>
