<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 { CustomsBroker } from './columns.js';
	import DetailsDialog from './details-dialog.svelte';
	import DeleteDialog from './delete-dialog.svelte';
	import { goto } from '$app/navigation';

	let {
		broker,
		onSuccess
	}: {
		broker: CustomsBroker;
		onSuccess?: () => void;
	} = $props();

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

	function handleCopyKey() {
		navigator.clipboard.writeText(broker.broker_key);
	}

	function handleCopyTaxId() {
		if (broker.tax_id) {
			navigator.clipboard.writeText(broker.tax_id);
		}
	}

	function handleViewDetails() {
		showDetailsDialog = true;
	}

	function handleDelete() {
		showDeleteDialog = true;
	}
</script>

<DropdownMenu.Root>
	<DropdownMenu.Trigger>
		{#snippet child({ props })}
			<Button {...props} variant="ghost" size="icon" class="relative h-8 w-8 p-0">
				<span class="sr-only">Abrir menú</span>
				<EllipsisIcon class="h-4 w-4" />
			</Button>
		{/snippet}
	</DropdownMenu.Trigger>
	<DropdownMenu.Content>
		<DropdownMenu.Group>
			<DropdownMenu.Label>Acciones</DropdownMenu.Label>
			<DropdownMenu.Item onclick={handleCopyKey}>Copiar clave</DropdownMenu.Item>
			{#if broker.tax_id}
				<DropdownMenu.Item onclick={handleCopyTaxId}>Copiar RFC</DropdownMenu.Item>
			{/if}
		</DropdownMenu.Group>
		<DropdownMenu.Separator />
		<DropdownMenu.Group>
			<DropdownMenu.Item onclick={handleViewDetails}>Ver detalles</DropdownMenu.Item>
			<DropdownMenu.Item
				onclick={() => goto(`/dashboard/customs_brokers/edit/${broker.broker_key}`)}
			>
				Editar
			</DropdownMenu.Item>
			<DropdownMenu.Item onclick={handleDelete} class="text-destructive">
				Eliminar
			</DropdownMenu.Item>
		</DropdownMenu.Group>
	</DropdownMenu.Content>
</DropdownMenu.Root>

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