<script lang="ts">
	import * as Tabs from '$lib/components/ui/tabs/index.js';
	import UploadLauncherGrid from '$lib/components/dashboard/csv-upload/UploadLauncherGrid.svelte';
	import ConfigFooter from '$lib/components/dashboard/csv-upload/ConfigFooter.svelte';
	import ProcessingResultModal from '$lib/components/dashboard/csv-upload/ProcessingResultModal.svelte';
	import {
		catalogosConfig,
		transportesConfig,
		importacionConfig,
		exportacionConfig,
		tabSettings,
		type CsvUploadItem
	} from '$lib/config/csv-upload';
	import { api } from '$lib/api';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';

	// We no longer need modal state
	let activeTab = $state('catalogos');

	let isUploading = $state(false);
	let currentJobId = $state<string | null>(null);
	let activeModelTarget = $state<string | null>(null);
	let scanResults = $state<any>(null);
	let commitResults = $state<any>(null);
	let showResultModal = $state(false);

	// Initialize settings for all tabs upfront to avoid reactivity loops
	let allSettings = $state<Record<string, any>>(() => {
		const initial: Record<string, any> = {};
		for (const tab in tabSettings) {
			initial[tab] = {};
			tabSettings[tab].forEach((f) => {
				initial[tab][f.name] = f.defaultValue;
			});
		}
		return initial;
	});

	async function handleUpload(file: File, config: CsvUploadItem) {
		isUploading = true;
		activeModelTarget = config.modelTarget || null;
		scanResults = null;
		const currentSettings = allSettings[activeTab] || {};
		const companyId = companyStore.activeCompany?.id || 1;
		const opType = activeTab === 'exportacion' ? 'exp' : 'imp';

		const res = await api.imports.upload(
			file,
			config.modelTarget || '',
			currentSettings,
			companyId,
			opType
		);
		if (res.data?.job_id) {
			currentJobId = res.data.job_id;
			pollStatus();
		} else {
			toast.error('Error al subir el archivo');
			isUploading = false;
		}
	}

	async function pollStatus() {
		if (!currentJobId) return;

		const res = await api.imports.status(currentJobId);
		if (res.data?.status === 'waiting_confirmation') {
			scanResults = res.data;
			showResultModal = true;
			toast.success('Escaneo completado. Revisa los resultados.');
			isUploading = false;
		} else if (res.data?.status === 'failed') {
			toast.error('Error en el procesamiento: ' + (res.data.error || 'Error desconocido'));
			isUploading = false;
			currentJobId = null;
			scanResults = null;
			commitResults = null;
			showResultModal = false;
		} else if (res.data?.status === 'warning') {
			// Caso cuando no se insertaron registros pero hay información de rechazo
			commitResults = res.data;
			showResultModal = true;
			const inserted = res.data?.inserted || 0;
			const skippedInvalid = res.data?.skipped_invalid || 0;
			const skippedFk = res.data?.skipped_missing_fk || 0;
			const totalSkipped = skippedInvalid + skippedFk;

			if (inserted === 0) {
				toast.error(`No se insertaron registros. ${totalSkipped} fueron rechazados.`);
			} else {
				toast.warning(`Solo se insertaron ${inserted} de ${inserted + totalSkipped} registros.`);
			}
			isUploading = false;
		} else if (res.data?.status === 'finished') {
			commitResults = res.data;
			showResultModal = true;
			const inserted = res.data?.inserted || 0;
			const skippedInvalid = res.data?.skipped_invalid || 0;
			const skippedFk = res.data?.skipped_missing_fk || 0;
			const skippedDetails = res.data?.skipped_details || [];

			if (inserted > 0) {
				toast.success(`Importación completada: ${inserted} registros insertados`);
				if (skippedInvalid > 0 || skippedFk > 0) {
					const totalSkipped = skippedInvalid + skippedFk;
					toast.warning(`${totalSkipped} registros fueron rechazados`);
				}
			} else {
				toast.error('No se insertaron registros. Revisa los errores a continuación.');
			}
			isUploading = false;
		} else {
			// Continue polling
			setTimeout(pollStatus, 2000);
		}
	}
</script>

<div class="flex flex-col h-[calc(100vh-4rem)] -m-4 overflow-hidden">
	<!-- Scrollable Content Area -->
	<div class="flex-1 overflow-y-auto p-4 md:p-8 space-y-4">
		<div class="flex items-center gap-4">
			<h1 class="text-lg font-semibold md:text-2xl">Importación Masiva de Datos (CSV)</h1>
		</div>

		<Tabs.Root bind:value={activeTab} class="w-full">
			<Tabs.List class="grid w-full grid-cols-2 md:grid-cols-4 lg:w-auto">
				<Tabs.Trigger value="catalogos">Catálogos</Tabs.Trigger>
				<Tabs.Trigger value="transportes">Transportes</Tabs.Trigger>
				<Tabs.Trigger value="importacion">Importación</Tabs.Trigger>
				<Tabs.Trigger value="exportacion">Exportación</Tabs.Trigger>
			</Tabs.List>

			<div class="mt-6">
				<Tabs.Content value="catalogos" class="space-y-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-medium tracking-tight">Catálogos Generales</h2>
					</div>
					<UploadLauncherGrid items={catalogosConfig} onUpload={handleUpload} />
				</Tabs.Content>

				<Tabs.Content value="transportes" class="space-y-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-medium tracking-tight">Logística y Transporte</h2>
					</div>
					<UploadLauncherGrid items={transportesConfig} onUpload={handleUpload} />
				</Tabs.Content>

				<Tabs.Content value="importacion" class="space-y-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-medium tracking-tight">Operaciones de Importación</h2>
					</div>
					<UploadLauncherGrid items={importacionConfig} onUpload={handleUpload} />
				</Tabs.Content>

				<Tabs.Content value="exportacion" class="space-y-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-medium tracking-tight">Operaciones de Exportación</h2>
					</div>
					<UploadLauncherGrid items={exportacionConfig} onUpload={handleUpload} />
				</Tabs.Content>
			</div>
		</Tabs.Root>

		<div class="h-4"></div>
	</div>

	<!-- Fixed Footer Area -->
	{#if allSettings[activeTab]}
		<div class="flex-none z-20">
			<ConfigFooter {activeTab} bind:settings={allSettings[activeTab]} />
		</div>
	{/if}
</div>

<ProcessingResultModal
	bind:open={showResultModal}
	{scanResults}
	{commitResults}
	{isUploading}
	onConfirm={async () => {
		if (currentJobId && activeModelTarget) {
			try {
				isUploading = true;
				const res = await api.imports.commit(currentJobId, activeModelTarget);
				if (res.data?.commit_job_id) {
					currentJobId = res.data.commit_job_id;
					pollStatus();
				}
			} catch (err) {
				toast.error('Error al iniciar la importación');
				isUploading = false;
			}
		}
	}}
	onCancel={() => {
		currentJobId = null;
		scanResults = null;
		commitResults = null;
		showResultModal = false;
	}}
	onClose={() => {
		currentJobId = null;
		scanResults = null;
		commitResults = null;
		showResultModal = false;
	}}
/>
