<script lang="ts">
    import { Button } from "$lib/components/ui/button";
    import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
    import { deleteCompany, type Company } from "$lib/api/dashboard/a76/general_catalogs/company";
    import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
    import CreateEditDialog from "./create-edit-dialog.svelte";
    import { goto } from "$app/navigation";

    let {
        item,
        onSuccess
    }: {
        item: Company;
        onSuccess?: () => void;
    } = $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 empresa "${item.name}"?\n\nNota: No se puede eliminar si tiene registros relacionados.`)) {
            return;
        }

        loading = true;
        error = null;

        try {
            const response = await deleteCompany(item.id);

            // Si hay error en la respuesta
            if (response.error) {
                return;
            }

            // Éxito (status 204 o 200)
            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>
        <DropdownMenu.Item onclick={() => goto(`/dashboard/general_catalogs/company_information/edit/${item.id}`)}> 
            <Pencil class="mr-2 h-4 w-4" />
            Editar
        </DropdownMenu.Item>
        <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>
    </DropdownMenu.Content>
</DropdownMenu.Root>
