<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import { Progress } from '$lib/components/ui/progress';
	import { invoicesReportsApi } from '$lib/api/dashboard/a76/reports/reports-invoices';
	import { toast } from 'svelte-sonner';
	import { Loader2, CheckCircle2, XCircle, FileDown } from 'lucide-svelte';
	import { Button } from '$lib/components/ui/button';

	export let open = false;
	export let taskId: string | null = null;
	export let onClose: () => void;
	export let onComplete: (result: any) => void;
	export let title: string = 'Generando PDF';

	export let getStatus: ((taskId: string) => Promise<any>) | null = null;

	let progress = 0;
	let statusMessage = 'Iniciando...';
	let pollingInterval: any = null;
	let isComplete = false;
	let hasError = false;

	// Reiniciar estado cuando se abre el diálogo con un nuevo taskId
	$: if (open && taskId) {
		progress = 0;
		statusMessage = 'Iniciando...';
		isComplete = false;
		hasError = false;
		startPolling();
	} else if (!open) {
		stopPolling();
	}

	function stopPolling() {
		if (pollingInterval) {
			clearInterval(pollingInterval);
			pollingInterval = null;
		}
	}

	async function startPolling() {
		stopPolling(); // Asegurar limpieza previa

		pollingInterval = setInterval(async () => {
			if (!taskId) return;

			try {
				const apiCall = getStatus || invoicesReportsApi.getTaskStatus;
				const response = await apiCall(taskId);

				if (response.state === 'PROCESSING' && response.info) {
					progress = response.info.current || 0;
					statusMessage = response.info.status || 'Procesando...';
				} else if (response.state === 'SUCCESS') {
					progress = 100;
					statusMessage = '¡Completado!';
					isComplete = true;
					stopPolling();
					// Pequeña pausa para ver el 100%
					setTimeout(() => {
						onComplete(response.result);
					}, 500);
				} else if (response.state === 'FAILURE') {
					hasError = true;
					// Intenta mostrar el mensaje de error real si viene en 'result'
					const errMsg = response.result ? String(response.result) : 'Error desconocido';
					statusMessage = `Error: ${errMsg}`;
					stopPolling();
					toast.error(`Falló la generación: ${errMsg}`);
					console.error('Task failed with result:', response);
				}
			} catch (error) {
				console.error('Error polling task status:', error);
				// No detenemos el polling inmediatamente por un error de red transitorio,
				// pero podríamos contar intentos fallidos si fuera necesario.
			}
		}, 1000);
	}

	function handleOpenChange(newOpen: boolean) {
		if (!newOpen) {
			stopPolling();
			onClose();
		}
	}
</script>

<Dialog.Root bind:open onOpenChange={handleOpenChange}>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>{title}</Dialog.Title>
			<Dialog.Description>Por favor espere mientras se genera su documento.</Dialog.Description>
		</Dialog.Header>

		<div class="flex flex-col gap-6 py-6">
			<div class="mb-1 flex items-center justify-between text-sm">
				<span class="text-muted-foreground">{statusMessage}</span>
				<span class="font-medium">{progress}%</span>
			</div>

			<Progress value={progress} class="h-2 w-full" />

			<div class="flex h-16 items-center justify-center">
				{#if isComplete}
					<div
						class="animate-in fade-in zoom-in flex flex-col items-center text-green-600 duration-300"
					>
						<CheckCircle2 size={48} />
						<span class="mt-2 text-sm font-medium">Listo para descargar</span>
					</div>
				{:else if hasError}
					<div
						class="animate-in fade-in zoom-in flex flex-col items-center text-destructive duration-300"
					>
						<XCircle size={48} />
						<span class="mt-2 text-sm font-medium">Ocurrió un error</span>
					</div>
				{:else}
					<div class="flex animate-pulse flex-col items-center text-primary">
						<FileDown size={48} class="opacity-50" />
					</div>
				{/if}
			</div>
		</div>

		<Dialog.Footer>
			{#if hasError}
				<Button variant="secondary" onclick={onClose}>Cerrar</Button>
			{/if}
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
