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

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

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

    async function handleDelete() {
        if (!canDelete) return;
        if (!confirm('¿Está seguro de que desea eliminar esta ubicación?')) {
            return;
        }

        const companyId = companyStore.activeCompany?.id;
        if (!companyId) {
            alert('❌ Error: No hay compañía seleccionada');
            return;
        }

        loading = true;

        try {
            await deleteLocation(item.id, companyId);
            alert('✅ Ubicación eliminada correctamente');
            if (onSuccess) {
                onSuccess();
            }
        } catch (err: any) {
            error = err.message || 'Error al eliminar la ubicación';
            alert(`❌ Error: ${error}`);
            console.error('Error deleting:', err);
        } finally {
            loading = false;
        }
    }

    function handleEdit() {
        if (!canEdit) return;
        selectedItem = item;
        dialogOpen = true;
    }

    function handleDialogSuccess() {
        dialogOpen = false;
        selectedItem = null;
        if (onSuccess) {
            onSuccess();
        }
    }
</script>

<DropdownMenu.Root>
    <DropdownMenu.Trigger>
        {#snippet child({ props })}
            <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
                <span class="sr-only">Abrir menú</span>
                <EllipsisVertical size={16} />
            </Button>
        {/snippet}
    </DropdownMenu.Trigger>
    <DropdownMenu.Content align="end" class="w-[160px]">
        <DropdownMenu.Label>Acciones</DropdownMenu.Label>
        <DropdownMenu.Separator />
        <DropdownMenu.Item onclick={handleEdit} disabled={!canEdit}>
            <Pencil size={16} class="mr-2" />
            Editar
        </DropdownMenu.Item>
        <DropdownMenu.Separator />
        <DropdownMenu.Item onclick={handleDelete} class="text-destructive" disabled={loading || !canDelete}>
            {#if loading}
                <LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
            {:else}
                <Trash2 size={16} class="mr-2" />
            {/if}
            Eliminar
        </DropdownMenu.Item>
    </DropdownMenu.Content>
</DropdownMenu.Root>

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