<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { Label } from '$lib/components/ui/label/index.js';
	import { Upload, FileType } from 'lucide-svelte';
	import type { CsvUploadItem } from '$lib/config/csv-upload';

	let {
		open = $bindable(false),
		config,
		currentSettings // Read-only prop passed from page
	}: {
		open: boolean;
		config: CsvUploadItem;
		currentSettings: Record<string, any>;
	} = $props();

	// State
	let file: File | null = $state(null);
	let isProcessing = $state(false);

	function handleFileChange(e: Event) {
		const target = e.target as HTMLInputElement;
		if (target.files && target.files.length > 0) {
			file = target.files[0];
		}
	}

	function handleProcess() {
		isProcessing = true;
		console.log('Processing Upload Request:', {
			entityConfig: config,
			file: file,
			activeSettings: currentSettings // Log the global/tab settings being applied
		});

		// Mock processing time
		setTimeout(() => {
			isProcessing = false;
			open = false;
			alert(
				`Procesando archivo para: ${config.title}\nConfiguración aplicada: ${JSON.stringify(currentSettings, null, 2)}`
			);
		}, 1000);
	}

	// Reset file state when config changes or modal opens
	$effect(() => {
		if (config) {
			file = null;
		}
	});
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[500px]">
		<Dialog.Header>
			<Dialog.Title class="flex items-center gap-2">
				{#if config.icon}
					<config.icon class="h-5 w-5" />
				{/if}
				Importar {config.title}
			</Dialog.Title>
			<Dialog.Description>
				Selecciona tu archivo CSV para procesar.
				<br />
				<span class="text-xs text-muted-foreground mt-1 block">
					La configuración activa del pie de página se aplicará a esta carga.
				</span>
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid gap-6 py-4">
			<!-- Stage 1: File Selection -->
			<div class="flex flex-col gap-3">
				<div
					class="border-2 border-dashed rounded-lg p-8 flex flex-col items-center justify-center gap-2 hover:bg-muted/50 transition-colors cursor-pointer relative"
				>
					<input
						type="file"
						accept=".csv,.txt"
						class="absolute inset-0 opacity-0 cursor-pointer"
						onchange={handleFileChange}
					/>
					{#if file}
						<FileType class="h-12 w-12 text-primary" />
						<div class="text-center">
							<span class="font-medium text-sm block">{file.name}</span>
							<span class="text-xs text-muted-foreground">{(file.size / 1024).toFixed(2)} KB</span>
						</div>
					{:else}
						<Upload class="h-10 w-10 text-muted-foreground" />
						<span class="font-medium text-sm">Arrastra tu archivo aquí o haz clic</span>
						<span class="text-xs text-muted-foreground">Soporta CSV, TXT</span>
					{/if}
				</div>
			</div>

			<!-- Preview of Current Settings (Read Only) -->
			{#if Object.keys(currentSettings).length > 0}
				<div class="bg-muted/40 p-3 rounded text-xs text-muted-foreground">
					<strong>Configuración Activa:</strong>
					<ul class="list-disc pl-4 mt-1 space-y-0.5">
						{#each Object.entries(currentSettings) as [key, value]}
							<li>{key}: <span class="font-mono">{value}</span></li>
						{/each}
					</ul>
				</div>
			{/if}
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
			<Button onclick={handleProcess} disabled={!file || isProcessing}>
				{#if isProcessing}
					Procesando...
				{:else}
					Procesar
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
