<script lang="ts">
	import { Button } from "$lib/components/ui/button";
	import * as AlertDialog from "$lib/components/ui/alert-dialog";
	import { containersApi, type Container } from "$lib/api/dashboard/refrence_data/containers";
	import { LoaderCircle } from 'lucide-svelte';

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

	let loading = $state(false);
	let error = $state<string | null>(null);

	async function handleDelete() {
		if (!item) return;

		loading = true;
		error = null;

		try {
			const response = await containersApi.delete(Number(item.key));

			if (response.error) {
				error = response.error;
				return;
			}

			// Éxito
			open = false;
			if (onSuccess) {
				onSuccess();
			}
		} catch (e) {
			error = e instanceof Error ? e.message : "Error al eliminar";
			console.error("Error deleting:", e);
		} finally {
			loading = false;
		}
	}

	function handleOpenChange(newOpen: boolean) {
		if (!newOpen) {
			error = null;
		}
		open = newOpen;
	}
</script>

<AlertDialog.Root bind:open onOpenChange={handleOpenChange}>
	<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 este contenedor:</p>
				{#if item}
					<div class="mt-2 rounded-lg bg-muted p-3 space-y-1">
						<div class="flex items-center justify-between text-sm">
							<span class="font-medium">Código:</span>
							<key class="font-mono">{item.key}</key>
						</div>
						<div class="flex items-center justify-between text-sm">
							<span class="font-medium">Descripción:</span>
							<span class="truncate max-w-[200px]">{item.description}</span>
						</div>
					</div>
				{/if}
				{#if error}
					<div class="mt-2 rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
						{error}
					</div>
				{/if}
			</AlertDialog.Description>
		</AlertDialog.Header>
		<AlertDialog.Footer>
			<AlertDialog.Cancel disabled={loading}>Cancelar</AlertDialog.Cancel>
			<AlertDialog.Action
				onclick={handleDelete}
				disabled={loading}
				class="bg-destructive text-destructive-foreground hover:bg-destructive/90"
			>
				{#if loading}
					<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
				{/if}
				Eliminar
			</AlertDialog.Action>
		</AlertDialog.Footer>
	</AlertDialog.Content>
</AlertDialog.Root>
