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

    interface Props {
        unit: UnitOfMeasureCustoms;
        onSuccess?: () => void;
    }

    let { unit, onSuccess }: Props = $props();
    let dialogOpen = $state(false);

    async function handleDelete() {
        if (!confirm('¿Estás seguro de eliminar esta unidad?')) return;
        
        const activeCompanyId = companyStore.activeCompany?.id;
        if (!activeCompanyId) {
            return;
        }

        const response = await deleteUnitOfMeasureCustoms(unit.id, activeCompanyId);
        if (response.error) {
        } else if (response.status === 204 || response.status === 200) {
            onSuccess?.();
        }
    }
</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>
                <MoreHorizontal class="h-4 w-4" />
            </Button>
        {/snippet}
    </DropdownMenu.Trigger>
    <DropdownMenu.Content align="end">
        <DropdownMenu.Label>Acciones</DropdownMenu.Label>
        <DropdownMenu.Item onclick={() => (dialogOpen = true)}>
            <Pencil class="mr-2 h-4 w-4" />
            Editar
        </DropdownMenu.Item>
        <DropdownMenu.Separator />
        <DropdownMenu.Item onclick={handleDelete}>
            <Trash2 class="mr-2 h-4 w-4" />
            Eliminar
        </DropdownMenu.Item>
    </DropdownMenu.Content>
</DropdownMenu.Root>

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