<script lang="ts">
    import EllipsisIcon from "@lucide/svelte/icons/ellipsis";
    import { Button } from "$lib/components/ui/button/index.js";
    import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
    import type { ClientProvider } from "./columns.js";
    import DetailsDialog from "./details-dialog.svelte";
    import DeleteDialog from "./delete-dialog.svelte";
    import { clientsProvidersApi } from "$lib/api/dashboard/a76/clients-providers";
    import { companyStore } from "$lib/stores/company.svelte";
    import { goto } from "$app/navigation"; 

    let { 
        item,
        onSuccess
    }: { 
        item: ClientProvider;
        onSuccess?: () => void;
    } = $props();

    let showDetailsDialog = $state(false);
    let showDeleteDialog = $state(false);
    let isToggling = $state(false);

    function handleCopyId() {
        navigator.clipboard.writeText(item.id.toString());
    }

    function handleCopyRfc() {
        navigator.clipboard.writeText(item.rfc);
    }

    function handleViewDetails() {
        showDetailsDialog = true;
    }

    function handleDelete() {
        showDeleteDialog = true;
    }

    async function handleToggleStatus() {
        if (isToggling || !companyStore.activeCompany) return;

        isToggling = true;
        try {
            const response = await clientsProvidersApi.toggleStatus(item.id, companyStore.activeCompany.id);
            
            if (response.error) {
                console.error('Error toggling status:', response.error);
                alert(`Error: ${response.error}`);
            } else {
                if (onSuccess) {
                    onSuccess();
                }
            }
        } catch (error) {
            console.error('Error toggling status:', error);
            alert('Error cambiando el estado');
        } finally {
            isToggling = false;
        }
    }
</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>
                <EllipsisIcon class="size-4" />
            </Button>
        {/snippet}
    </DropdownMenu.Trigger>
    <DropdownMenu.Content align="end">
        <DropdownMenu.Group>
            <DropdownMenu.Label>Acciones</DropdownMenu.Label>
            <DropdownMenu.Item onclick={handleCopyId}>
                Copiar ID
            </DropdownMenu.Item>
            <DropdownMenu.Item onclick={handleCopyRfc}>
                Copiar RFC
            </DropdownMenu.Item>
        </DropdownMenu.Group>
        <DropdownMenu.Separator />
        <DropdownMenu.Item onclick={handleViewDetails}>Ver detalles</DropdownMenu.Item>
        
        <DropdownMenu.Item onclick={() => goto(`/dashboard/clients_and_providers/edit/${item.id}`)}>
            Editar
        </DropdownMenu.Item>
        <DropdownMenu.Item onclick={handleToggleStatus} disabled={isToggling}>
            {isToggling ? 'Cambiando...' : item.is_active === true ? 'Desactivar' : 'Activar'}
        </DropdownMenu.Item>
        <DropdownMenu.Separator />
        <DropdownMenu.Item class="text-destructive" onclick={handleDelete}>Eliminar</DropdownMenu.Item>
    </DropdownMenu.Content>
</DropdownMenu.Root>

<DetailsDialog bind:open={showDetailsDialog} {item} />
<DeleteDialog bind:open={showDeleteDialog} {item} {onSuccess} />