<script lang="ts">
	import { appSettingsApi } from '$lib/api/dashboard/a76/app-settings';
	import { toast } from 'svelte-sonner';
	import { Settings2, Save, RefreshCw, Database, Package } from 'lucide-svelte';
	import { companyStore } from '$lib/stores/company.svelte';
	import { currentUser, userHasPermission } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	// Componentes UI
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Badge } from '$lib/components/ui/badge';

	// Custom Components
	import SsisGenTabsForm from '$lib/components/dashboard/settings/SsisGenTabsForm.svelte';
	import QsisGenTabsForm from '$lib/components/dashboard/settings/QsisGenTabsForm.svelte';

	let tenantIdVal = $derived(companyStore.activeCompany?.tenant_id || 0);
	let companyIdVal = $derived(companyStore.activeCompany?.id || 0);

	// SCAII (ssisgen) | SCAF (qsisgen)
	type SystemType = 'ssisgen' | 'qsisgen';
	let activeSystem = $state<SystemType>('ssisgen');

	let resolvedSettings = $state<any>(null);
	let loading = $state(true);
	let saving = $state(false);

	let currentFormData = $state<any>({});

	// Permissions
	const canView = $derived(userHasPermission($currentUser, 'settings_general.view'));
	const canEdit = $derived(userHasPermission($currentUser, 'settings_general.edit'));

	$effect(() => {
		const companyId = companyIdVal;
		const tenantId = tenantIdVal;
		if (companyId && tenantId && canView) {
			handleResolve();
		} else if (!canView) {
			loading = false;
		} else {
			loading = true;
			resolvedSettings = null;
			currentFormData = {};
		}
	});

	async function handleSave() {
		if (!canEdit) {
			toast.error('No tienes permiso para guardar cambios (settings_general.edit requerido)');
			return;
		}
		if (!companyIdVal || !tenantIdVal) {
			toast.error('No hay contexto de empresa o tenant activo');
			return;
		}
		saving = true;
		try {
			const payload = {
				tenant_id: tenantIdVal,
				company_id: companyIdVal,
				settings: {
					[activeSystem]: {
						...currentFormData,
						Type: activeSystem === 'ssisgen' ? 'SCAII' : 'SCAF'
					}
				}
			};
			await appSettingsApi.upsert(payload);
			toast.success(`Configuraciones de ${activeSystem.toUpperCase()} guardadas correctamente`);
			await handleResolve();
		} catch (e: any) {
			toast.error('Error al guardar: ' + e.message);
		} finally {
			saving = false;
		}
	}

	async function handleResolve() {
		if (!companyIdVal || !tenantIdVal || !canView) return;
		loading = true;
		try {
			resolvedSettings = await appSettingsApi.getResolved(tenantIdVal, companyIdVal);
			// Carga los datos del sistema activo — sin $effect duplicado
			currentFormData = resolvedSettings?.[activeSystem]
				? { ...resolvedSettings[activeSystem] }
				: {};
		} catch (e: any) {
			toast.error('Error al cargar configuraciones: ' + e.message);
		} finally {
			loading = false;
		}
	}

	function handleFormUpdate(newData: any) {
		currentFormData = newData;
	}

	function switchSystem(sys: SystemType) {
		if (sys === activeSystem) return;
		activeSystem = sys;
		// Usa los datos ya cargados en caché; no hace re-fetch
		if (resolvedSettings) {
			currentFormData = resolvedSettings[sys] ? { ...resolvedSettings[sys] } : {};
		} else {
			currentFormData = {};
		}
	}
</script>

<svelte:head>
	<title>Configuración General | Anexo 76</title>
</svelte:head>

<div class="container mx-auto py-6 pb-32">
	{#if !canView}
		<ErrorState status={403} />
	{:else}
		<div class="mb-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
			<div>
				<h1 class="text-2xl font-bold tracking-tight">Configuraciones Generales</h1>
				<p class="text-muted-foreground">
					Configura los parámetros del sistema.
				</p>
			</div>

			<!-- Toggle SCAII / SCAF -->
			<div class="flex items-center gap-2 bg-muted rounded-lg p-1 w-fit">
				<button
					onclick={() => switchSystem('ssisgen')}
					class="flex items-center gap-2 px-4 py-2 rounded-md text-sm font-semibold transition-all duration-200
						{activeSystem === 'ssisgen'
							? 'bg-background text-foreground shadow-sm'
							: 'text-muted-foreground hover:text-foreground'}"
				>
					<Database class="w-4 h-4" />
					SCAII
					{#if activeSystem === 'ssisgen'}
						<Badge variant="secondary" class="text-[10px] px-1.5 py-0 ml-1">inv</Badge>
					{/if}
				</button>
				<button
					onclick={() => switchSystem('qsisgen')}
					class="flex items-center gap-2 px-4 py-2 rounded-md text-sm font-semibold transition-all duration-200
						{activeSystem === 'qsisgen'
							? 'bg-background text-foreground shadow-sm'
							: 'text-muted-foreground hover:text-foreground'}"
				>
					<Package class="w-4 h-4" />
					SCAF
					{#if activeSystem === 'qsisgen'}
						<Badge variant="secondary" class="text-[10px] px-1.5 py-0 ml-1">fixed_asset</Badge>
					{/if}
				</button>
			</div>
		</div>

		{#if loading && !resolvedSettings}
			<div class="flex flex-col items-center justify-center py-12 gap-4">
				<RefreshCw class="w-8 h-8 animate-spin text-primary" />
				<p class="text-muted-foreground">Cargando configuraciones...</p>
			</div>
		{:else}
			<div class="grid gap-6">
				<div class="bg-background rounded-lg border p-4">
					{#if activeSystem === 'ssisgen'}
						<SsisGenTabsForm
							currentData={currentFormData}
							onUpdate={handleFormUpdate}
						/>
					{:else}
						<QsisGenTabsForm
							currentData={currentFormData}
							onUpdate={handleFormUpdate}
						/>
					{/if}
				</div>
			</div>
		{/if}
	{/if}
</div>

{#if canView}
	<!-- Sticky Footer -->
	<div class="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur border-t shadow-lg z-10 p-4 transition-all duration-300 group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]">
		<div class="container mx-auto max-w-[1400px] flex justify-end items-center gap-4">
			{#if loading}
				<div class="text-sm text-muted-foreground flex items-center gap-2">
					<RefreshCw class="w-4 h-4 animate-spin" />
					Cargando...
				</div>
			{/if}
			{#if canEdit}
				<Button onclick={handleSave} disabled={saving || loading}>
					{#if saving}
						<RefreshCw class="mr-2 h-4 w-4 animate-spin" />
						Guardando...
					{:else}
						<Save class="mr-2 h-4 w-4" />
						Guardar {activeSystem === 'ssisgen' ? 'SCAII' : 'SCAF'}
					{/if}
				</Button>
			{:else}
				<p class="text-xs text-muted-foreground italic">
					(Solo lectura: se requiere <span class="font-mono">settings_general.edit</span> para guardar)
				</p>
			{/if}
		</div>
	</div>
{/if}
