<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import * as AlertDialog from '$lib/components/ui/alert-dialog';
	import { Loader2 } from 'lucide-svelte';
	import { manifestApi, type Manifest } from '$lib/api/dashboard/a76/manifests';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';

	let {
		open = $bindable(false),
		manifest,
		onSuccess
	}: { open: boolean; manifest: Manifest | null; onSuccess?: () => void } = $props();

	let loading = $state(false);

	async function handleDelete() {
		if (!manifest || !companyStore.activeCompany) return;

		try {
			loading = true;
			const response = await manifestApi.delete(
				companyStore.activeCompany.id.toString(),
				manifest.id
			);
			if (response.error) {
				toast.error(response.error);
				return;
			}
			toast.success('Manifiesto eliminado correctamente');
			open = false;
			onSuccess?.();
		} catch (error) {
			console.error(error);
			toast.error('Error al eliminar el manifiesto');
		} finally {
			loading = false;
		}
	}
</script>

<AlertDialog.Root bind:open>
	<AlertDialog.Content>
		<AlertDialog.Header>
			<AlertDialog.Title>¿Estás seguro?</AlertDialog.Title>
			<AlertDialog.Description class="space-y-2">
				<p>Esta acción no se puede deshacer. Se eliminará permanentemente el manifiesto:</p>
				{#if manifest}
					<div class="mt-2 rounded-lg bg-muted p-3">
						<div class="flex items-center justify-between text-sm">
							<span class="font-medium">Manifiesto:</span>
							<code class="font-mono font-semibold">{manifest.manifest_number}</code>
						</div>
						<div class="mt-1 truncate text-xs text-muted-foreground">
							{manifest.description || 'Sin descripción'}
						</div>
					</div>
				{/if}
			</AlertDialog.Description>
		</AlertDialog.Header>
		<AlertDialog.Footer>
			<AlertDialog.Cancel disabled={loading}>Cancelar</AlertDialog.Cancel>
			<AlertDialog.Action
				onclick={handleDelete}
				disabled={loading}
				class="text-destructive-foreground bg-destructive hover:bg-destructive/90"
			>
				{#if loading}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Eliminando...
				{:else}
					Eliminar
				{/if}
			</AlertDialog.Action>
		</AlertDialog.Footer>
	</AlertDialog.Content>
</AlertDialog.Root>
