<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 "$lib/api/dashboard/a76/clients-providers";
    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,
        canEdit = false,
        canDelete = false
    }: { 
        item: ClientProvider;
        onSuccess?: () => void;
        canEdit?: boolean;
        canDelete?: boolean;
    } = $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);
    }

    const isForeign = (cp: ClientProvider) =>
        (cp.type_nat_foreign || "N").toUpperCase() === "E";

    function handleViewDetails() {
        showDetailsDialog = true;
    }

    function handleDelete() {
        showDeleteDialog = true;
    }

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

        isToggling = true;
        try {
            const nextActive = item.is_active !== true;
            const response = await clientsProvidersApi.update(item.id, companyStore.activeCompany.id, {
                is_active: nextActive
            });
            
            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 {isForeign(item) ? 'TAX-ID' : 'RFC'}
            </DropdownMenu.Item>
        </DropdownMenu.Group>
        <DropdownMenu.Separator />
        <DropdownMenu.Item onclick={handleViewDetails}>Ver detalles</DropdownMenu.Item>
        {#if canEdit}
        <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>
        {/if}
        {#if canDelete}
        <DropdownMenu.Separator />
        <DropdownMenu.Item class="text-destructive" onclick={handleDelete}>Eliminar</DropdownMenu.Item>
        {/if}
    </DropdownMenu.Content>
</DropdownMenu.Root>

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