<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 { onMount } from 'svelte';

	// Tipo extendido que combina A76Class y FAClass
	interface FixedAssetClassExtended extends A76Class {
		fa_class_id?: number;
		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
	let classes = $state<FixedAssetClassExtended[]>([]);
	let selectedClass = $state<FixedAssetClassExtended | null>(null);
	let isLoading = $state(false);
	let searchTerm = $state('');
	let searchDescription = $state('');
	let searchType = $state('');
	let searchFraction = $state('');
	let showInsertDialog = $state(false);
	let showDeleteDialog = $state(false);
	let validationError = $state<string>('');
	let isSaving = $state(false);

	// 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: ''
	});

	// Clases filtradas según búsqueda
	const filteredClasses = $derived(
		classes.filter((c) => {
			// Filtro por código de clase
			const matchesCode =
				!searchTerm || c.class_code.toLowerCase().includes(searchTerm.toLowerCase());

			// Filtro por descripción (español o inglés)
			const matchesDescription =
				!searchDescription ||
				(c.description_es?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false) ||
				(c.description_en?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false);

			// Filtro por tipo de material
			const matchesType =
				!searchType || (c.material_key?.toLowerCase().includes(searchType.toLowerCase()) ?? false);

			// Filtro por fracción arancelaria
			const matchesFraction =
				!searchFraction ||
				(c.fraction?.toLowerCase().includes(searchFraction.toLowerCase()) ?? false);

			return matchesCode && matchesDescription && matchesType && matchesFraction;
		})
	);

	// Reactively load classes when company changes
	$effect(() => {
		const companyId = companyStore.activeCompany?.id;
		if (companyId) {
			loadClasses();
		}
	});

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

		isLoading = true;
		try {
			// Use the new consolidated endpoint that fetches classes + FA data in ONE query
			const response = await classesApi.getWithFAData({
				company_id: companyId,
				page: 1,
				page_size: 1000
			});

			if (response.data) {
				// Data already comes with FA fields embedded
				classes = response.data as FixedAssetClassExtended[];
			}
		} catch (error) {
			console.error('Error cargando clases:', error);
			toast.error('Error al cargar las clases de activo fijo');
		} finally {
			isLoading = false;
		}
	}

	function selectClass(cls: A76Class) {
		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: 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 handleNew() {
		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: ''
		};
	}

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

	function handleDelete() {
		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();

			selectedClass = null;
			showDeleteDialog = false;
			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: ''
			};
		} 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: () => {
				handleNew();
				validationError = '';
				showInsertDialog = true;
			}
		},
		{
			key: 'Alt+Shift+R',
			description: 'Refresh',
			action: handleRefresh
		},
		{
			key: 'Alt+Shift+D',
			description: 'Delete',
			action: handleDelete
		}
	]);
</script>

<div class="flex h-[calc(100vh-4rem)] flex-col gap-4 p-4 pb-15">
	<!-- Título -->
	<div class="flex flex-col gap-1">
		<h1 class="text-2xl font-bold">CATALOGO DE CLASES DE ACTIVO FIJO</h1>
		<p class="text-sm text-muted-foreground">Gestiona y consulta las clases de activo fijo</p>
	</div>

	<!-- Contenedor principal con grid y detalles -->
	<div class="flex flex-1 gap-4 overflow-hidden">
		<!-- Panel izquierdo: Grid/Tabla de clases -->
		<div class="flex flex-1 flex-col gap-4 overflow-hidden">
			<!-- Sección de Filtros -->
			<div class="rounded-lg border bg-card">
				<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" />
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Descripción</Label>
							<Input
								bind:value={searchDescription}
								placeholder="Buscar descripción..."
								class="h-9"
							/>
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Tipo</Label>
							<Input bind:value={searchType} placeholder="MP, SC, DESP..." class="h-9" />
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Fracción</Label>
							<Input bind:value={searchFraction} placeholder="Fracción arancelaria" class="h-9" />
						</div>
					</div>
				</div>
			</div>

			<!-- Tabla de clases -->
			<div class="flex flex-1 flex-col overflow-hidden rounded-lg border">
				<div class="flex items-center justify-between border-b bg-white p-3 dark:bg-muted/50">
					<h2 class="text-sm font-semibold">Listado de Clases</h2>
					<div class="flex items-center gap-2">
						<span class="text-xs text-muted-foreground">
							Mostrando de {filteredClasses.length} registros
						</span>
						<Button variant="outline" size="sm" onclick={handleRefresh}>
							<RefreshCw class="mr-2 h-4 w-4" />
							Actualizar
						</Button>
					</div>
				</div>

				<!-- Tabla de clases -->
				<div class="flex-1 overflow-auto">
					<table class="w-full text-sm">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="w-8 px-2 py-2 text-left">
									<input type="checkbox" class="h-4 w-4" />
								</th>
								<th class="px-2 py-2 text-left">Clase</th>
								<th class="px-2 py-2 text-left">Descripción Español</th>
								<th class="px-2 py-2 text-left">Descripción Inglés</th>
								<th class="px-2 py-2 text-left">Tipo</th>
								<th class="px-2 py-2 text-left">U.M</th>
								<th class="px-2 py-2 text-left">Fracción</th>
								<th class="px-2 py-2 text-left">U.M.T.</th>
								<th class="px-2 py-2 text-left">Fracción US</th>
							</tr>
						</thead>
						<tbody>
							{#if isLoading}
								<tr>
									<td colspan="10" class="py-8 text-center text-muted-foreground">Cargando...</td>
								</tr>
							{:else if filteredClasses.length === 0}
								<tr>
									<td colspan="10" class="py-8 text-center text-muted-foreground">
										No hay clases de activo fijo registradas
									</td>
								</tr>
							{:else}
								{#each filteredClasses as cls (cls.id)}
									<tr
										class="cursor-pointer border-b transition-colors {selectedClass?.id === cls.id
											? 'bg-gray-300 dark:bg-gray-600'
											: 'hover:bg-gray-100 dark:hover:bg-gray-700'}"
										onclick={() => selectClass(cls)}
									>
										<td class="px-2 py-1">
											<input
												type="checkbox"
												checked={selectedClass?.id === cls.id}
												class="h-4 w-4"
											/>
										</td>
										<td class="px-2 py-1">
											<span
												class="inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-2 py-1 font-mono text-xs font-bold text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
											>
												{cls.class_code}
											</span>
										</td>
										<td class="px-2 py-1 text-sm font-medium">{cls.description_es || ''}</td>
										<td class="px-2 py-1">{cls.description_en || ''}</td>
										<td class="px-2 py-1">
											<span
												class="rounded-full px-2 py-0.5 text-[10px] font-bold tracking-wider uppercase {cls.material_key ===
												'MP'
													? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
													: cls.material_key === 'SC'
														? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400'
														: cls.material_key === 'DESP'
															? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
															: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400'}"
											>
												{cls.material_key || ''}
											</span>
										</td>
										<td class="px-2 py-1 text-muted-foreground">{cls.unit_of_measure || ''}</td>
										<td class="px-2 py-1 font-mono text-xs text-orange-600 dark:text-orange-400"
											>{cls.fraction || ''}</td
										> <td class="px-2 py-1 text-xs text-muted-foreground">-</td>
										<td class="px-2 py-1">{cls.us_fraction || '-'}</td>
									</tr>
								{/each}
							{/if}
						</tbody>
					</table>
				</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">
						{formData.fraction || '0000.00.00'}
					</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>
</div>

<!-- Footer fijo con botones de acción -->
<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">
			<Button
				size="sm"
				onclick={() => {
					selectedClass = null;
					validationError = '';
					showInsertDialog = true;
				}}
			>
				<Plus class="mr-1 h-4 w-4" />
				Insertar
			</Button>
			<Button
				variant="outline"
				size="sm"
				onclick={() => {
					if (!selectedClass) {
						toast.error('Selecciona una clase para editar');
						return;
					}
					validationError = '';
					showInsertDialog = true;
				}}
				disabled={!selectedClass}>Editar</Button
			>
			<Button variant="outline" size="sm" onclick={handleDelete} disabled={!selectedClass}
				>Borrar</Button
			>
		</div>
	</div>
</div>

<!-- 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;
					}
					isSaving = true;
					validationError = '';

					try {
						const cleanData = $state.snapshot(data);
						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: cleanData.fraction?.trim() || '',
									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,
										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: cleanData.fraction?.trim() || '',
								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;
						selectedClass = null;
						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>
