<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Dialog from '$lib/components/ui/dialog';
	import FixedAssetClassForm from '$lib/components/dashboard/goods/classes/forms/FixedAssetClassForm.svelte';
	import { Folder, Save, Plus, RefreshCw } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { classesApi, type A76Class } from '$lib/api/dashboard/a76/classes';
	import { faClassesApi, type FAClass } from '$lib/api/dashboard/a24/fa_classes';
	import { companyStore } from '$lib/stores/company.svelte';
	import DataTable from '$lib/components/dashboard/goods/classes/data-table.svelte';
	import { columns } from '$lib/components/dashboard/goods/classes/columns';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import {
		canCreateGoodsClasses,
		canDeleteGoodsClasses,
		canEditGoodsClasses,
		canViewGoodsClasses
	} from '$lib/permissions/goods-classes-permissions';
	import {
		formatMexTariffDigitsForDisplay,
		normalizeMexTariffDigitsStored
	} from '$lib/utils/mexican-tariff-fraction';

	// Tipo extendido que combina A76Class y FAClass
	interface FixedAssetClassExtended extends A76Class {
		fa_class_id?: number;
		import_tariff_code?: string | null;
		import_tariff_type?: string | null;
		export_tariff_code?: string | null;
		export_tariff_type?: string | null;
		depreciation_rate?: number | null;
		fda_code?: string | null;
		eccn_code?: string | null;
		class_enabled?: boolean | null;
		// Virtual fields for form compatibility
		annual_depreciation_rate?: number | string | null;
		fda_key?: string | null;
	}

	// Estado de la lista de clases (servidor: filtros + paginación)
	let classes = $state<FixedAssetClassExtended[]>([]);
	let selectedClassIds = $state<number[]>([]);
	let selectedClass = $state<FixedAssetClassExtended | null>(null);
	let isLoading = $state(false);
	let searchTerm = $state('');
	let searchDescription = $state('');
	let searchType = $state('');
	let searchFraction = $state('');
	const PAGE_SIZE = 50;
	let currentPage = $state(1);
	let totalItems = $state(0);
	let debouncedFilters = $state({
		class_code: '',
		description: '',
		material_key: '',
		fraction: ''
	});
	let lastCompanyId = $state<number | undefined>(undefined);
	let loadSeq = 0;
	let showInsertDialog = $state(false);
	let showDeleteDialog = $state(false);
	let validationError = $state<string>('');
	let isSaving = $state(false);
	let sorting = $state<import("@tanstack/table-core").SortingState>([]);
	let status = $state<number>(200);

	// Permisos
	const canView = $derived(canViewGoodsClasses($currentUser));
	const canCreate = $derived(canCreateGoodsClasses($currentUser));
	const canEdit = $derived(canEditGoodsClasses($currentUser));
	const canDelete = $derived(canDeleteGoodsClasses($currentUser));

	const isError = $derived(!canView || status >= 400);

	// Estado del formulario
	let formData = $state({
		class_code: '',
		description_es: '',
		description_en: '',
		material_key: '',
		unit_of_measure: '',
		fraction: '',
		us_fraction: '',
		unit_measure_trade: '',
		depreciation_rate: null as number | null,
		fda_code: '',
		eccn_code: '',
		bom: ''
	});

	const totalPages = $derived(Math.max(1, Math.ceil(totalItems / PAGE_SIZE)));
	const rangeStart = $derived(totalItems === 0 ? 0 : (currentPage - 1) * PAGE_SIZE + 1);
	const rangeEnd = $derived(Math.min(currentPage * PAGE_SIZE, totalItems));

	$effect(() => {
		const companyId = companyStore.activeCompany?.id;
		if (companyId === undefined) return;
		if (lastCompanyId !== undefined && lastCompanyId !== companyId) {
			currentPage = 1;
		}
		lastCompanyId = companyId;
	});

	$effect(() => {
		const s = searchTerm;
		const d = searchDescription;
		const t = searchType;
		const f = searchFraction;
		const handle = setTimeout(() => {
			const next = {
				class_code: s,
				description: d,
				material_key: t,
				fraction: f
			};
			const same =
				debouncedFilters.class_code === next.class_code &&
				debouncedFilters.description === next.description &&
				debouncedFilters.material_key === next.material_key &&
				debouncedFilters.fraction === next.fraction;
			if (!same) {
				debouncedFilters = next;
				currentPage = 1;
			}
		}, 400);
		return () => clearTimeout(handle);
	});

	async function loadClasses() {
		if (!canView) return;
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			return;
		}

		const seq = ++loadSeq;
		isLoading = true;
		try {
			const response = await classesApi.getWithFAData({
				company_id: companyId,
				page: currentPage,
				page_size: PAGE_SIZE,
				sort_by: sorting.length > 0 ? String(sorting[0].id) : undefined,
				sort_order: sorting.length > 0 ? (sorting[0].desc ? 'desc' : 'asc') : undefined,
				...(debouncedFilters.class_code.trim() && {
					class_code: debouncedFilters.class_code.trim()
				}),
				...(debouncedFilters.description.trim() && {
					description: debouncedFilters.description.trim()
				}),
				...(debouncedFilters.material_key.trim() && {
					material_key: debouncedFilters.material_key.trim()
				}),
				...(debouncedFilters.fraction.trim() && { fraction: debouncedFilters.fraction.trim() })
			});

			if (seq !== loadSeq) return;

			if (response.data) {
				classes = response.data.items as FixedAssetClassExtended[];
				totalItems = response.data.total;
				handleSelectedIdsChange(
					selectedClassIds.filter((id) => classes.some((item) => item.id === id))
				);
			}
			status = 200;
		} catch (error: any) {
			console.error('Error cargando clases:', error);
			if (error?.response?.status) {
				status = error.response.status;
			} else if (error?.status) {
				status = error.status;
			}
			toast.error('Error al cargar las clases de activo fijo');
		} finally {
			if (seq === loadSeq) {
				isLoading = false;
			}
		}
	}

	$effect(() => {
		if (!canView) return;
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		void currentPage;
		void debouncedFilters;
		void sorting;
		loadClasses();
	});

	function selectClass(cls: A76Class) {
		if (!canView) return;
		selectedClass = cls as FixedAssetClassExtended;
		formData = {
			class_code: cls.class_code,
			description_es: cls.description_es || '',
			description_en: cls.description_en || '',
			material_key: cls.material_key || '',
			unit_of_measure: cls.unit_of_measure || '',
			fraction: cls.fraction || '',
			us_fraction: cls.us_fraction || '',
			unit_measure_trade: '',
			depreciation_rate: (cls as FixedAssetClassExtended).depreciation_rate || null,
			fda_code: (cls as FixedAssetClassExtended).fda_code || '',
			eccn_code: (cls as FixedAssetClassExtended).eccn_code || '',
			bom: ''
		};
	}

	function clearSelectedClass() {
		selectedClass = null;
		formData = {
			class_code: '',
			description_es: '',
			description_en: '',
			material_key: '',
			unit_of_measure: '',
			fraction: '',
			us_fraction: '',
			unit_measure_trade: '',
			depreciation_rate: null as number | null,
			fda_code: '',
			eccn_code: '',
			bom: ''
		};
	}

	function setActiveClass(cls: FixedAssetClassExtended | null) {
		if (!cls) {
			clearSelectedClass();
			return;
		}

		selectedClass = cls;
		formData = {
			class_code: cls.class_code,
			description_es: cls.description_es || '',
			description_en: cls.description_en || '',
			material_key: cls.material_key || '',
			unit_of_measure: cls.unit_of_measure || '',
			fraction: normalizeMexTariffDigitsStored(
				(cls as FixedAssetClassExtended).import_tariff_code || cls.fraction || ''
			),
			us_fraction: cls.us_fraction || '',
			unit_measure_trade: '',
			depreciation_rate: (cls as FixedAssetClassExtended).depreciation_rate || null,
			fda_code: (cls as FixedAssetClassExtended).fda_code || '',
			eccn_code: (cls as FixedAssetClassExtended).eccn_code || '',
			bom: ''
		};
	}

	function handleSelectedIdsChange(ids: number[]) {
		selectedClassIds = ids;
		const primaryId = ids[0];
		const primaryClass = primaryId
			? classes.find((item) => item.id === primaryId) ?? null
			: null;

		setActiveClass(primaryClass);
	}

	function handleRowDoubleClick(cls: A76Class) {
		if (!canEdit) {
			toast.error('No tienes permiso para editar clases de activo fijo');
			return;
		}
		const fixedClass = cls as FixedAssetClassExtended;
		selectedClassIds = [fixedClass.id, ...selectedClassIds.filter((id) => id !== fixedClass.id)];
		setActiveClass(fixedClass);
		validationError = '';
		showInsertDialog = true;
	}

	function handleNew() {
		selectedClassIds = [];
		clearSelectedClass();
	}

	async function handleRefresh() {
		if (!canView) return;
		await loadClasses();
		toast.success('Clases actualizadas');
	}

	function handleDelete() {
		if (!canDelete) return;
		if (!selectedClass) {
			toast.error('Selecciona una clase para borrar');
			return;
		}
		showDeleteDialog = true;
	}

	async function confirmDelete() {
		if (!selectedClass) return;

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			toast.error('No hay empresa seleccionada');
			return;
		}

		const classToDelete = selectedClass;

		try {
			// El backend ahora elimina automáticamente la extensión FA si existe
			await classesApi.delete(classToDelete.id, companyId);

			toast.success(`Clase ${classToDelete.class_code} eliminada correctamente`);

			// Recargar lista
			await loadClasses();

			selectedClassIds = [];
			clearSelectedClass();
			showDeleteDialog = false;
		} catch (error) {
			console.error('Error deleting class:', error);
			toast.error('Error al eliminar la clase');
		}
	}

	// Keyboard Shortcuts
	import { useShortcuts } from '$lib/hooks/use-shortcuts';

	useShortcuts('Goods / Classes', [
		{
			key: 'Alt+Shift+N',
			description: 'New Class',
			action: () => {
				if (!canCreate) return;
				handleNew();
				validationError = '';
				showInsertDialog = true;
			}
		},
		{
			key: 'Alt+Shift+R',
			description: 'Refresh',
			action: handleRefresh
		},
		{
			key: 'Alt+Shift+D',
			description: 'Delete',
			action: () => {
				if (!canDelete) return;
				handleDelete();
			}
		},
		{
			key: 'Ctrl+S',
			description: 'Guardar clase',
			action: () => {
				if (!showInsertDialog || isSaving) return;
				const isEditMode = !!selectedClass?.id;
				if (isEditMode && !canEdit) {
					toast.error('No tienes permiso para editar clases');
					return;
				}
				if (!isEditMode && !canCreate) {
					toast.error('No tienes permiso para crear clases');
					return;
				}
				document.dispatchEvent(new CustomEvent('save-form'));
			}
		}
	]);
</script>

<div class="flex flex-col gap-6 p-6 h-[calc(100svh-4rem)] group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)] overflow-hidden">
	<div class="flex-none flex items-center justify-between">
		<div class="space-y-1">
			<h1 class="text-2xl font-bold tracking-tight">Clases de Activo Fijo</h1>
			<p class="text-muted-foreground">Gestiona y consulta las clases de activo fijo</p>
		</div>
		<div class="flex items-center gap-3">
			<Button variant="outline" size="sm" class="h-9" onclick={handleRefresh}>
				<RefreshCw class="mr-2 h-4 w-4" />
				Actualizar
			</Button>
			{#if !isError && canCreate}
			<Button class="h-9" onclick={handleNew}>
				<Plus class="mr-2 h-4 w-4" />
				Nueva Clase
			</Button>
			{/if}
		</div>
	</div>

	{#if isError}
		<ErrorState
			status={!canView ? 403 : status}
			error={!canView ? 'Permission denied: goods_classes.view' : ''}
			onRetry={loadClasses}
		/>
	{:else}
	<!-- Contenedor principal con grid y detalles -->
	<div class="flex min-h-0 flex-1 gap-4 overflow-hidden">
		<!-- Panel izquierdo: Grid/Tabla de clases -->
		<div class="flex min-h-0 flex-1 flex-col gap-4 overflow-hidden">
			<!-- Sección de Filtros -->
			<div class="rounded-md border bg-background">
				<div class="space-y-4 p-4">
					<div class="flex items-center justify-between">
						<h2 class="text-sm font-semibold">Filtros</h2>
						<span class="text-xs text-muted-foreground">
							Filtra las clases por diferentes criterios (los filtros se aplican automáticamente)
						</span>
					</div>
					<div class="grid grid-cols-4 gap-4">
						<div class="space-y-2">
							<Label class="text-xs">Clase</Label>
							<Input bind:value={searchTerm} placeholder="Ej: AF001" class="h-9 bg-card" />
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Descripción</Label>
							<Input
								bind:value={searchDescription}
								placeholder="Buscar descripción..."
								class="h-9 bg-card"
							/>
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Tipo</Label>
							<Input bind:value={searchType} placeholder="MP, SC, DESP..." class="h-9 bg-card" />
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Fracción</Label>
							<Input bind:value={searchFraction} placeholder="Fracción arancelaria" class="h-9 bg-card" />
						</div>
					</div>
				</div>
			</div>

			<!-- Tabla de clases -->
			<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border bg-background">
				<div class="flex items-center justify-between border-b bg-background/95 p-3">
					<h2 class="text-sm font-semibold">Listado de Clases</h2>
					<div class="flex items-center gap-2">
						<span class="text-xs text-muted-foreground">
							{#if totalItems === 0}
								Sin resultados
							{:else}
								Mostrando {rangeStart}–{rangeEnd} de {totalItems} (pág. {currentPage}/{totalPages})
							{/if}
						</span>
						<Button variant="outline" size="sm" class="h-9" onclick={handleRefresh}>
							<RefreshCw class="mr-2 h-4 w-4" />
							Actualizar
						</Button>
					</div>
				</div>

				<!-- Tabla de clases -->
				<div class="flex min-h-0 flex-1 flex-col overflow-hidden p-0">
					<div class="min-h-0 flex-1 overflow-hidden">
						<DataTable
							data={classes}
							{columns}
							loading={isLoading}
							selectedIds={selectedClassIds}
							onSelectedIdsChange={handleSelectedIdsChange}
							onRowDoubleClick={handleRowDoubleClick}
							{sorting}
							onSortingChange={(newSorting) => {
								sorting = newSorting;
								currentPage = 1;
							}}
						/>
					</div>
					<div
						class="flex flex-none flex-wrap items-center justify-between gap-2 border-t bg-muted/20 px-3 py-2"
					>
						<span class="text-xs text-muted-foreground">
							{PAGE_SIZE} por página
						</span>
						<div class="flex items-center gap-2">
							<Button
								variant="outline"
								size="sm"
								class="h-8"
								disabled={currentPage <= 1 || isLoading}
								onclick={() => {
									currentPage = Math.max(1, currentPage - 1);
								}}
							>
								Anterior
							</Button>
							<Button
								variant="outline"
								size="sm"
								class="h-8"
								disabled={currentPage >= totalPages || isLoading || totalItems === 0}
								onclick={() => {
									currentPage = Math.min(totalPages, currentPage + 1);
								}}
							>
								Siguiente
							</Button>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- Panel derecho: Detalles y edición -->
		<div class="flex w-96 flex-none flex-col overflow-hidden rounded-xl border bg-muted/30 shadow-sm">
			<div class="border-b p-4">
				<p class="text-[10px] tracking-widest text-muted-foreground uppercase opacity-80">
					Código de Clase
				</p>
				<h2 class="font-mono text-3xl font-black tracking-tighter">
					{formData.class_code || '---'}
				</h2>
			</div>

			<div class="flex-1 space-y-6 overflow-auto bg-card p-5">
				<div class="space-y-3">
					<div>
						<Label class="text-[10px] font-bold text-muted-foreground uppercase"
							>Descripción ES</Label
						>
						<p class="text-sm leading-tight font-semibold">
							{formData.description_es || 'Sin descripción'}
						</p>
					</div>
					<div class="border-t border-dashed pt-2">
						<Label class="text-[10px] font-bold text-muted-foreground uppercase"
							>Description EN</Label
						>
						<p class="text-sm text-muted-foreground italic">
							{formData.description_en || 'No translation available'}
						</p>
					</div>
				</div>

				<div class="grid grid-cols-2 gap-4 border-t pt-4">
					<div class="space-y-1">
						<Label class="text-[10px] font-bold text-muted-foreground uppercase">Tipo Activo</Label>
						<div class="flex items-center gap-2">
							<Folder class="h-3 w-3 text-blue-500" />
							<span class="text-sm font-bold">{formData.material_key || '-'}</span>
						</div>
					</div>
					<div class="space-y-1">
						<Label class="text-[10px] font-bold text-muted-foreground uppercase">U.M. Com.</Label>
						<span class="text-sm font-bold">{formData.unit_of_measure || '-'}</span>
					</div>
				</div>

				<div
					class="rounded-lg border border-orange-100 bg-orange-50 p-3 dark:border-orange-900 dark:bg-orange-950/20"
				>
					<Label class="text-[10px] font-bold text-orange-600 uppercase dark:text-orange-400"
						>Fracción Arancelaria</Label
					>
					<p class="font-mono text-lg font-bold text-orange-700 dark:text-orange-300">
						{formatMexTariffDigitsForDisplay(formData.fraction) || '—'}
					</p>
				</div>

				<!-- ECCN Field in Detail Panel -->
				<div
					class="rounded-lg border border-blue-100 bg-blue-50 p-3 dark:border-blue-900 dark:bg-blue-950/20"
				>
					<Label class="text-[10px] font-bold text-blue-600 uppercase dark:text-blue-400"
						>Código ECCN</Label
					>
					<p class="font-mono text-lg font-bold text-blue-700 dark:text-blue-300">
						{formData.eccn_code || '---'}
					</p>
				</div>
			</div>
		</div>
	</div>
	{/if}
</div>

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

<!-- Footer fijo con botones de acción -->
{#if !isError}
<div
	class="fixed right-0 bottom-0 left-0 z-[5] border-t bg-background/95 shadow-lg backdrop-blur supports-[backdrop-filter]:bg-background/80"
>
	<div class="mx-auto max-w-[1400px] px-4 py-4">
		<!-- Botones de acción -->
		<div class="flex justify-end gap-2">
			{#if canCreate}
			<Button
				size="sm"
				onclick={() => {
					selectedClass = null;
					validationError = '';
					showInsertDialog = true;
				}}
			>
				<Plus class="mr-1 h-4 w-4" />
				Insertar
			</Button>
			{/if}
			{#if canEdit}
			<Button
				variant="outline"
				size="sm"
				onclick={() => {
					if (!selectedClass) {
						toast.error('Selecciona una clase para editar');
						return;
					}
					validationError = '';
					showInsertDialog = true;
				}}
				disabled={!selectedClass}>Editar</Button
			>
			{/if}
			{#if canDelete}
			<Button variant="outline" size="sm" onclick={handleDelete} disabled={!selectedClass}
				>Borrar</Button
			>
			{/if}
		</div>
	</div>
</div>
{/if}

<!-- Dialog para Insertar/Editar Clase de Activo Fijo -->
<Dialog.Root bind:open={showInsertDialog}>
	<Dialog.Content class="flex h-[90vh] w-full max-w-6xl flex-col overflow-hidden p-0">
		<Dialog.Header class="border-b p-6 pb-4">
			<Dialog.Title>{selectedClass ? 'Editar' : 'Nueva'} Clase de Activo Fijo</Dialog.Title>
		</Dialog.Header>

		<!-- Mensaje de error de validación -->
		{#if validationError}
			<div class="mx-6 mt-4 rounded-lg border border-red-200 bg-red-50 p-4">
				<div class="flex items-start gap-3">
					<div
						class="mt-0.5 flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full bg-red-500 text-sm font-bold text-white"
					>
						!
					</div>
					<div class="flex-1">
						<h3 class="mb-1 text-sm font-semibold text-red-800">Error de Validación</h3>
						<p class="text-sm whitespace-pre-line text-red-700">{validationError}</p>
					</div>
					<button
						onclick={() => (validationError = '')}
						class="flex-shrink-0 text-red-400 hover:text-red-600"
						aria-label="Cerrar mensaje de error"
					>
						<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M6 18L18 6M6 6l12 12"
							/>
						</svg>
					</button>
				</div>
			</div>
		{/if}

		<div class="flex-1 overflow-auto p-6">
			<FixedAssetClassForm
				initialData={selectedClass}
				externalError={validationError}
				onClearError={() => (validationError = '')}
				onSave={async (data: Partial<FixedAssetClassExtended>) => {
					// Evitar múltiples clics
					if (isSaving) {
						return;
					}
					if (selectedClass?.id && !canEdit) {
						toast.error('No tienes permiso para editar clases');
						return;
					}
					if (!selectedClass?.id && !canCreate) {
						toast.error('No tienes permiso para crear clases');
						return;
					}
					isSaving = true;
					validationError = '';

					try {
						const cleanData = $state.snapshot(data);
						const mxFraccionNorm = normalizeMexTariffDigitsStored(
							String(cleanData.import_tariff_code || cleanData.fraction || '').trim()
						);
						const companyId = companyStore.activeCompany?.id;

						if (!companyId) {
							throw new Error('No hay empresa seleccionada');
						}

						let response;

						if (selectedClass?.id) {
							// === ACTUALIZACIÓN ===

							response = await classesApi.update(
								selectedClass.id,
								{
									class_code: cleanData.class_code?.trim() || '',
									description_es: cleanData.description_es?.trim() || '',
									description_en: cleanData.description_en?.trim() || '',
									material_key: cleanData.material_key?.trim() || '',
									unit_of_measure: cleanData.unit_of_measure?.trim() || '',
									fraction: mxFraccionNorm,
									us_fraction: cleanData.us_fraction || '',
									physical_review: cleanData.physical_review ? 1 : 0,
									iva_exempt_fraction: cleanData.iva_exempt_fraction || ''
								},
								companyId
							);

							// También actualizar la extensión FA
							if (selectedClass.fa_class_id) {
								await faClassesApi.update(
									selectedClass.fa_class_id,
									{
										depreciation_rate:
											cleanData.annual_depreciation_rate !== undefined &&
											cleanData.annual_depreciation_rate !== null &&
											cleanData.annual_depreciation_rate !== ''
												? Number(cleanData.annual_depreciation_rate)
												: cleanData.depreciation_rate !== undefined &&
													  cleanData.depreciation_rate !== null &&
													  cleanData.depreciation_rate != null
													? Number(cleanData.depreciation_rate)
													: null,
										import_tariff_code: mxFraccionNorm || null,
										import_tariff_type: cleanData.import_tariff_type || null,
										export_tariff_code: cleanData.export_tariff_code || null,
										export_tariff_type: cleanData.export_tariff_type || null,
										fda_code: (cleanData.fda_key ?? cleanData.fda_code) || null,
										eccn_code: cleanData.eccn_code || null
									},
									companyId
								);
							} else {
								await faClassesApi.create(
									{
										class_id: selectedClass.id,
										depreciation_rate:
											cleanData.annual_depreciation_rate !== undefined &&
											cleanData.annual_depreciation_rate !== null &&
											cleanData.annual_depreciation_rate !== ''
												? Number(cleanData.annual_depreciation_rate)
												: cleanData.depreciation_rate !== undefined &&
													  cleanData.depreciation_rate !== null &&
													  cleanData.depreciation_rate != null
													? Number(cleanData.depreciation_rate)
													: null,
										fda_code: (cleanData.fda_key ?? cleanData.fda_code) || null,
										eccn_code: cleanData.eccn_code || null,
										class_enabled: true
									},
									companyId
								);
							}

							// ¡IMPORTANTE! fetchApi NO lanza excepciones, retorna { error, status }
							if (response.error) {
								console.error('❌ Error en respuesta de actualización:', response);
								throw new Error(response.error);
							}
						} else {
							// === CREACIÓN ===
							const payload = {
								class_code: cleanData.class_code?.trim() || '',
								description_es: cleanData.description_es?.trim() || '',
								description_en: cleanData.description_en?.trim() || '',
								material_key: cleanData.material_key?.trim() || '',
								unit_of_measure: cleanData.unit_of_measure?.trim() || '',
								fraction: mxFraccionNorm,
								us_fraction: cleanData.us_fraction?.trim() || '',
								sub_key: cleanData.sub_key || '',
								physical_review: cleanData.physical_review ? 1 : 0,
								iva_exempt_fraction: cleanData.iva_exempt_fraction || '',
								depreciation_rate:
									cleanData.annual_depreciation_rate !== undefined &&
									cleanData.annual_depreciation_rate !== null &&
									cleanData.annual_depreciation_rate !== ''
										? Number(cleanData.annual_depreciation_rate)
										: cleanData.depreciation_rate !== undefined &&
											  cleanData.depreciation_rate !== null &&
											  cleanData.depreciation_rate != null
											? Number(cleanData.depreciation_rate)
											: null,
								fda_code: (cleanData.fda_key ?? cleanData.fda_code) || null,
								eccn_code: cleanData.eccn_code || null,
								class_enabled: true
							};

							response = await classesApi.createFA(payload, companyId);

							if (response.error) {
								console.error('❌ Error del servidor:', response.error);
								throw new Error(response.error);
							}
						}

						// === ÉXITO TOTAL ===
						const wasUpdate = !!selectedClass?.id;
						await loadClasses();
						showInsertDialog = false;
						selectedClassIds = [];
						clearSelectedClass();
						validationError = '';
						toast.success(
							wasUpdate ? 'Clase actualizada correctamente' : 'Clase creada correctamente'
						);
					} catch (error: any) {
						// === ERROR ===
						console.error('========================================');
						console.error('❌ ERROR CAPTURADO');
						console.error('Error:', error);
						console.error('Error.response:', error?.response);
						console.error('Error.response.data:', error?.response?.data);
						console.error('Error.detail:', error?.detail);
						console.error('========================================');

						let errorMsg = 'Error al guardar';

						// Primero intentar con error.detail (fetch directo)
						if (error?.detail) {
							if (typeof error.detail === 'string') {
								errorMsg = error.detail;
							} else if (Array.isArray(error.detail)) {
								errorMsg = error.detail.map((e: any) => e.msg || e).join(', ');
							}
						}
						// Luego con error.response.data.detail (axios)
						else if (error?.response?.data?.detail) {
							if (typeof error.response.data.detail === 'string') {
								errorMsg = error.response.data.detail;
							} else if (Array.isArray(error.response.data.detail)) {
								errorMsg = error.response.data.detail.map((e: any) => e.msg || e).join(', ');
							}
						}
						// Por último el mensaje genérico
						else if (error?.message) {
							errorMsg = error.message;
						}

						console.error('📝 Mensaje de error extraído:', errorMsg);

						validationError = errorMsg;
						console.error('🔴 validationError asignado:', validationError);
						console.error('🔴 showInsertDialog permanece:', showInsertDialog);
						console.error('========================================');

						// NO cerramos el diálogo, permanece abierto
					} finally {
						isSaving = false;
					}
				}}
				onCancel={() => {
					showInsertDialog = false;
					selectedClass = null;
				}}
			/>
		</div>
		<Dialog.Footer class="border-t p-6 pt-4">
			<Button
				variant="outline"
				onclick={() => {
					validationError = '';
					showInsertDialog = false;
					selectedClass = null;
				}}>Cancelar</Button
			>
			<Button
				type="button"
				disabled={isSaving}
				onclick={() => {
					// Trigger the form's handleSave by getting a reference via DOM
					const saveEvent = new CustomEvent('save-form');
					document.dispatchEvent(saveEvent);
				}}
			>
				{#if isSaving}
					<RefreshCw class="mr-2 h-4 w-4 animate-spin" />
					Guardando...
				{:else}
					<Save class="mr-2 h-4 w-4" />
					Guardar
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Dialog de confirmación para borrar -->
<Dialog.Root bind:open={showDeleteDialog}>
	<Dialog.Content class="max-w-md">
		<Dialog.Header>
			<Dialog.Title>¿Confirmar eliminación?</Dialog.Title>
		</Dialog.Header>
		<div class="py-4">
			<p class="text-sm text-muted-foreground">
				¿Estás seguro que deseas eliminar la clase <strong class="text-foreground"
					>{selectedClass?.class_code}</strong
				>?
			</p>
			<p class="mt-2 text-sm text-muted-foreground">
				{selectedClass?.description_es}
			</p>
			<p class="mt-4 text-sm text-destructive">Esta acción no se puede deshacer.</p>
		</div>
		<Dialog.Footer>
			<Button variant="outline" onclick={() => (showDeleteDialog = false)}>Cancelar</Button>
			<Button variant="destructive" onclick={confirmDelete}>Eliminar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
