<script lang="ts">
	import { Button } from "$lib/components/ui/button";
	import * as AlertDialog from "$lib/components/ui/alert-dialog";
	import { clientsProvidersApi, type ClientProvider } from "$lib/api/dashboard/a76/clients-providers";
	import { companyStore } from "$lib/stores/company.svelte";
	import { LoaderCircle } from 'lucide-svelte';

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

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

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

		loading = true;
		error = null;

		try {
			const response = await clientsProvidersApi.delete(item.id, companyStore.activeCompany.id);

			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;
	}

	const isForeign = (cp: ClientProvider) =>
		(cp.type_nat_foreign || "N").toUpperCase() === "E";
</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 cliente/proveedor:</p>
				{#if item}
					<div class="mt-2 rounded-lg bg-muted p-3 space-y-2">
						<div class="flex items-center justify-between text-sm">
							<span class="font-medium">ID:</span>
							<span class="font-semibold">{item.id}</span>
						</div>
						<div class="flex items-center justify-between text-sm">
							<span class="font-medium">{item ? (isForeign(item) ? 'TAX-ID:' : 'RFC:') : 'RFC:'}</span>
							<code class="font-mono font-semibold">{item.rfc}</code>
						</div>
						<div class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Nombre:</span>
							<span class="text-xs">{item.name}</span>
						</div>
						<div class="flex items-center justify-between text-sm">
							<span class="font-medium">Tipo:</span>
							<span class="text-xs">
								{item.client_or_provider === 'client' ? 'Cliente' : 
								 item.client_or_provider === 'provider' ? 'Proveedor' : 
								 item.client_or_provider === 'both' ? 'Ambos' : 'N/A'}
							</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>
