<script lang="ts">
	import * as Table from '$lib/components/ui/table';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Textarea } from '$lib/components/ui/textarea';
	import { Badge } from '$lib/components/ui/badge';
	import {
		Plus,
		Pencil,
		Trash2,
		Loader2,
		Save as SaveIcon,
		Sparkles,
		Search,
		PackageOpen,
		Calendar,
		LayoutTemplate,
		X
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import { itemsApi, type Item } from '$lib/api/dashboard/a76/items';
	import { companyStore } from '$lib/stores/company.svelte';
	import ItemSheetFa from './fa/item-sheet-fa.svelte';
	import ItemSheetInv from './inv/item-sheet-inv.svelte';
	import { itemPresetsApi, type ItemPreset } from '$lib/api/dashboard/a76/item-presets';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { cleanLineData } from '$lib/utils/items-logic';

	let {
		invoice,
		formData = $bindable(),
		exists = $bindable(),
		operationType = undefined,
		invoiceType = undefined
	}: {
		invoice: Invoice | null;
		formData?: any;
		exists?: boolean;
		operationType?: number;
		invoiceType?: string;
	} = $props();

	// 1. Core State
	let items = $state<Item[]>([]);
	let displayedItems = $state<any[]>([]);
	let imported = $state(0);
	let net_weight = $state(0);
	let gross_weight = $state(0);
	let itemsPerPage = 20;
	let currentPage = $state(1);

	// 2. Preset State
	let presets = $state<ItemPreset[]>([]);
	let selectedPreset = $state<ItemPreset | null>(null);
	let searchPresets = $state('');
	let isLoadingPresets = $state(false);
	let isApplyingPreset = $state(false);
	let showUsePresetDialog = $state(false);
	// Preset Creation State
	let showCreatePresetDialog = $state(false);
	let createPresetName = $state('');
	let createPresetDescription = $state('');
	let builderItems: any[] = $state([]);
	let isSavingPreset = $state(false);
	let isTargetingPreset = $state(false);
	let editingBuilderIndex = $state<number | null>(null);

	// 3. Selection & Filtering State
	let selectedLineIds = $state<string[]>([]);
	let focusedLine = $state<any>(null);

	// 4. Derived Values (Ordered correctly to avoid TDZ)
	const flattenedLines = $derived.by(() => {
		const sourceItems = items?.length ? items : formData?.items || [];
		return (sourceItems || []).map((item: any, itemIndex: number) => ({
			...item,
			id: item?.id || `item-${itemIndex}`,
			line_number: item?.line_number ?? itemIndex + 1,
			reference_number: item?.reference_number,
			is_subitem: item?.is_subitem ?? false,
			class_code: item?.class_code ?? item?.class_id,
			class_description:
				item?.class_description ||
				item?.description?.description_spanish ||
				item?.description?.description_english ||
				'',
			unit_of_measure_code: item?.quantity?.unit_of_measure || item?.unit_of_measure,
			part_number_display: (item as any).part_number_display || item?.part_number,
			fa_data: item?.fa_data || {},
			warehouse: item?.warehouse,
			full_item: item
		}));
	});

	const isAllSelected = $derived(
		flattenedLines.length > 0 && selectedLineIds.length === flattenedLines.length
	);

	const invoiceSystem = $derived(invoice?.system || 'scaii');
	const invoiceLabel = $derived.by(() => {
		if (invoice?.invoice_number) return `Factura ${invoice.invoice_number}`;
		if (invoice?.id) return `Factura ${invoice.id}`;
		return 'Factura nueva';
	});

	const filteredPresets = $derived.by(() => {
		const term = searchPresets.trim().toLowerCase();
		if (!term) return presets;
		return presets.filter(
			(p: ItemPreset) =>
				p.name.toLowerCase().includes(term) || p.description?.toLowerCase().includes(term)
		);
	});

	const selectedPresetItems = $derived(selectedPreset?.items || []);
	const selectedPresetCount = $derived(selectedPresetItems.length);
	const activeCompanyId = $derived(companyStore?.activeCompany?.id);
	const formItemsCount = $derived(formData?.items?.length || 0);

	// 5. UI State
	let tableContainer = $state<HTMLDivElement>();
	let isLoadingMore = $state(false);
	let isLoadingItems = $state(false);
	let isSaving = $state(false);

	// 6. Form/Sheet State
	let showItemSheet = $state(false);
	let isEditMode = $state(false);
	let showDeleteDialog = $state(false);
	let selectedItem = $state<Item | null>(null);
	let originalItemData = $state<Partial<Item> | null>(null);
	let editingItem = $state<Partial<Item>>({
		invoice_id: undefined,
		reference_number: '',
		order: '',
		warehouse: '',
		location: ''
	});
	let builderDraft = $state({
		description: '',
		quantity: 1,
		unit_cost_usd: 0,
		reference_number: ''
	});

	// 7. Effects
	$effect(() => {
		currentPage = 1;
		displayedItems = flattenedLines.slice(0, itemsPerPage);
	});

	$effect(() => {
		if (invoice?.id && activeCompanyId) {
			loadItems();
		}
	});

	$effect(() => {
		if (invoice?.id && activeCompanyId && formItemsCount > 0) {
			loadItems();
		}
	});

	// 8. Functions
	function toggleSelectAll() {
		if (isAllSelected) {
			selectedLineIds = [];
		} else {
			selectedLineIds = flattenedLines.map((l: any) => l.id.toString());
		}
	}

	function toggleSelectLine(id: string) {
		if (selectedLineIds.includes(id)) {
			selectedLineIds = selectedLineIds.filter((i) => i !== id);
		} else {
			selectedLineIds = [...selectedLineIds, id];
		}
	}

	async function loadItems() {
		if (!invoice?.id || !activeCompanyId) return;

		isLoadingItems = true;
		try {
			const response = await itemsApi.listByInvoice(invoice.id, activeCompanyId);
			if (response.data) {
				items = response.data.items || [];
				currentPage = 1;
				// Wait for derived state to update before loading items
				await new Promise((resolve) => setTimeout(resolve, 0));
				loadMoreItems();
			}
		} catch (error: any) {
			console.error('Error loading items:', error);
			const errorMessage =
				error?.response?.data?.detail || 'No se pudieron cargar los items de la factura.';
			toast.error('Error al cargar items', {
				description: errorMessage
			});
		} finally {
			isLoadingItems = false;
		}
	}

	function loadMoreItems() {
		const start = 0;
		const end = currentPage * itemsPerPage;
		displayedItems = flattenedLines.slice(start, end);
		isLoadingMore = false;
	}

	function handleRowClick(line: any) {
		focusedLine = line;
	}

	function handleScroll(e: Event) {
		const target = e.target as HTMLDivElement;
		const threshold = 100;
		const scrolledToBottom =
			target.scrollHeight - target.scrollTop - target.clientHeight < threshold;

		if (scrolledToBottom && !isLoadingMore && displayedItems.length < flattenedLines.length) {
			isLoadingMore = true;
			currentPage++;
			loadMoreItems();
		}
	}

	function handleAdd() {
		// Validar que la factura esté guardada (tiene ID) si no estamos en modo plantilla
		if (!showCreatePresetDialog && !invoice?.id) {
			toast.warning('Factura no guardada', {
				description: 'Debes guardar la factura primero antes de agregar partidas.',
				duration: 5000
			});
			return;
		}

		isEditMode = false;
		isTargetingPreset = showCreatePresetDialog;
		editingBuilderIndex = null;
		showItemSheet = true;
		// Auto-asignar valores desde la factura con estructura completa
		editingItem = {
			invoice_id: invoice?.id,
			line_number: 1,
			// LineItem fields
			part_number: undefined,
			component_part_number: undefined,
			class_id: undefined,
			identifier: undefined,
			unit_of_measure: undefined,
			alternate_unit: undefined,
			permit_number: undefined,
			page_line: undefined,
			has_certificate: false,
			certificate_number: undefined,
			tax_payment: false,
			payment_method: undefined,
			igi_amount: undefined,
			is_military_mcia: false,
			wildcard_field: undefined,
			reference_number: '',
			order: invoice?.purchase_order || '',
			warehouse: '',
			location: '',
			// Nested relations
			financial: {
				unit_cost_usd: undefined,
				unit_cost_mxn: undefined,
				unit_cost_capture: undefined,
				unit_cost_commercial_usd: undefined,
				value_usd: undefined,
				value_mxn: undefined,
				value_returned_usd: undefined,
				value_returned_mxn: undefined,
				customs_value_usd: undefined
			},
			quantity: {
				quantity: undefined,
				unit_of_measure: undefined,
				quantity_temp_export: undefined,
				quantity_returned: undefined,
				net_weight: undefined,
				gross_weight: undefined,
				package_id: undefined,
				package_quantity: undefined,
				package_description: undefined
			},
			customs: {
				fraction: undefined,
				fraction_type: undefined,
				american_fraction: undefined,
				origin_country: undefined,
				destination_country: undefined,
				advalorem: undefined,
				advalorem_american: undefined,
				sector: undefined
			},
			description: {
				description_spanish: undefined,
				description_english: undefined,
				extra_description: undefined,
				additional_info_spanish: undefined,
				brand: undefined,
				model: undefined,
				has_serial: false,
				eighth_rule_fraction: undefined,
				eighth_rule_line: undefined,
				consider_a31: false,
				machinery_location: undefined
			},
			reference: {
				serie_id: undefined
			}
		};
	}

	async function loadPresets(force = false) {
		if (!activeCompanyId) return;
		if (!force && isLoadingPresets) return;
		isLoadingPresets = true;
		try {
			const response = await itemPresetsApi.list(activeCompanyId);
			presets = response.data || [];
			if (selectedPreset) {
				selectedPreset = presets.find((p) => p.id === selectedPreset?.id) || null;
			}
		} catch (error) {
			console.error('Error loading presets:', error);
			toast.error('No se pudieron cargar las plantillas');
		} finally {
			isLoadingPresets = false;
		}
	}

	function openUsePresetDialog() {
		if (!invoice?.id) {
			toast.warning('Primero guarda la factura para usar plantillas.');
			return;
		}
		showUsePresetDialog = true;
		if (!presets.length) void loadPresets();
	}

	function openCreatePresetDialog() {
		builderItems = [];
		createPresetName = '';
		createPresetDescription = '';
		isTargetingPreset = false;
		editingBuilderIndex = null;
		showCreatePresetDialog = true;
	}

	function handleEditInPreset(index: number) {
		const itemToEdit = builderItems[index];
		isEditMode = true;
		isTargetingPreset = true;
		editingBuilderIndex = index;
		editingItem = normalizeItemData(JSON.parse(JSON.stringify(itemToEdit)));
		showItemSheet = true;
	}

	function handleRemoveFromPreset(index: number) {
		builderItems = builderItems.filter((_: any, i: number) => i !== index);
	}

	function saveItemToPreset() {
		// Sanitizar datos para la plantilla
		let cleanedItem = JSON.parse(JSON.stringify(editingItem));

		// Limpiar item para asegurar que es compatible
		if (cleanedItem) {
			cleanedItem = {
				...cleanLineData(cleanedItem),
				id: undefined // Las plantillas no deben tener IDs reales
			};
		}

		if (editingBuilderIndex !== null) {
			// Update existing item in builder
			builderItems[editingBuilderIndex] = cleanedItem;
			toast.success('Partida actualizada en la plantilla');
		} else {
			// Add new item to builder
			builderItems = [...builderItems, cleanedItem];
			toast.success('Partida agregada a la plantilla');
		}

		showItemSheet = false;
		isTargetingPreset = false;
		editingBuilderIndex = null;
	}

	function sanitizeLineForPreset(line: any) {
		const { id, item_id, created_at, updated_at, temp_id, ...rest } = line || {};
		return cleanLineData({ ...rest });
	}

	function cloneItemForPreset(item: Item) {
		const { id, tenant_id, company_id, created_at, updated_at, temp_id, ...rest } = item as any;
		return {
			...sanitizeLineForPreset(rest),
			id: undefined,
			invoice_id: undefined
		};
	}

	function buildManualItem(draft: any, index: number) {
		return cleanLineData({
			id: undefined,
			temp_id: undefined,
			invoice_id: undefined,
			reference_number: draft.reference_number || undefined,
			line_number: index + 1,
			description: {
				description_spanish: draft.description || 'Sin descripción'
			},
			quantity: {
				quantity: Number(draft.quantity) || 0
			},
			financial: {
				unit_cost_usd: draft.unit_cost_usd !== null ? Number(draft.unit_cost_usd) || 0 : undefined
			}
		});
	}

	function handleAddManualItem() {
		if (!builderDraft.description.trim()) {
			toast.warning('Agrega una descripción para la partida');
			return;
		}
		const newItem = buildManualItem(builderDraft, builderItems.length);
		builderItems = [...builderItems, newItem];
		builderDraft = {
			description: '',
			quantity: 1,
			unit_cost_usd: 0,
			reference_number: ''
		};
	}

	async function applySelectedPreset() {
		if (!selectedPreset) {
			toast.warning('Selecciona una plantilla para aplicarla.');
			return;
		}
		if (!selectedPreset.items?.length) {
			toast.warning('Esta plantilla no tiene partidas.');
			return;
		}

		// Inject into active sheet if open
		// No se pueden inyectar múltiples líneas en un item, ya que ahora un item ES una línea
		if (showItemSheet) {
			toast.warning('No se puede inyectar plantilla en modo edición', {
				description: 'Las plantillas solo se pueden aplicar directamente a la factura'
			});
			showUsePresetDialog = false;
			return;
		}

		if (!invoice?.id || !activeCompanyId) {
			toast.warning('Primero guarda la factura para usar plantillas.');
			return;
		}

		isApplyingPreset = true;
		try {
			const payloads = selectedPreset.items.map((item) => ({
				...cloneItemForPreset(item),
				invoice_id: invoice.id
			}));

			await Promise.all(payloads.map((payload) => itemsApi.create(activeCompanyId, payload)));
			await loadItems();
			toast.success('Plantilla aplicada a la factura');
			showUsePresetDialog = false;
		} catch (error) {
			console.error('Error applying preset:', error);
			toast.error('No se pudo aplicar la plantilla');
		} finally {
			isApplyingPreset = false;
		}
	}

	async function saveCurrentItemsAsPreset() {
		if (!createPresetName.trim()) {
			toast.warning('Asigna un nombre a la plantilla');
			return;
		}
		if (!activeCompanyId) return;

		if (builderItems.length === 0) {
			toast.warning('No hay partidas o líneas para guardar como plantilla');
			return;
		}

		isSavingPreset = true;
		try {
			// We group everything as items for the template
			const lines = builderItems.map((item: Item, idx: number) => {
				return {
					...cleanLineData(item),
					line_number: item.line_number || idx + 1, // Ensure line_number is present
					id: undefined // Ensure no IDs are saved in the preset
				};
			});

			const payloadItems = [
				{
					reference_number: builderItems[0]?.reference_number || undefined,
					lines: lines
				}
			] as any;

			await itemPresetsApi.create(activeCompanyId, {
				name: createPresetName.trim(),
				description: createPresetDescription.trim() || undefined,
				items: payloadItems
			});

			createPresetName = '';
			createPresetDescription = '';
			builderItems = [];
			selectedLineIds = [];
			builderDraft = { description: '', quantity: 1, unit_cost_usd: 0, reference_number: '' };
			toast.success('Plantilla guardada correctamente');
			await loadPresets(true);
			showCreatePresetDialog = false;
		} catch (error) {
			console.error('Error saving preset:', error);
			toast.error('No se pudo guardar la plantilla');
		} finally {
			isSavingPreset = false;
		}
	}

	function handleEdit(lineData: any) {
		isEditMode = true;
		selectedItem = lineData.full_item;
		// Deep clone and normalize numeric values
		editingItem = normalizeItemData(JSON.parse(JSON.stringify(lineData.full_item)));
		// Guardar una copia del estado original para restaurar al cancelar
		originalItemData = JSON.parse(JSON.stringify(editingItem));
		// Enrich with descriptive data
		enrichItemData(editingItem);
		showItemSheet = true;
	}

	// Enrich item with descriptive data for display
	async function enrichItemData(item: Partial<Item>) {
		if (!item || !activeCompanyId) return;

		// Load class data
		if (item.class_id) {
			try {
				const response = await fetch(
					`/api-sveltekit/classes/${item.class_id}?company_id=${activeCompanyId}`,
					{ method: 'GET', headers: { 'Content-Type': 'application/json' } }
				);
				if (response.ok) {
					const classData = await response.json();
					(item as any).class_code = classData.class_code;
					(item as any).class_unit_of_measure = classData.unit_of_measure;
					(item as any).class_description = classData.description_es || classData.description_en;
				}
			} catch (error) {
				console.error('Error loading class data:', error);
			}
		}

		// Load part number data
		if (item.part_number_id) {
			try {
				const response = await fetch(
					`/api-sveltekit/parts/${item.part_number_id}?company_id=${activeCompanyId}`,
					{ method: 'GET', headers: { 'Content-Type': 'application/json' } }
				);
				if (response.ok) {
					const partData = await response.json();
					(item as any).part_number_display = partData.part_number;
					(item as any).part_description_es = partData.description_spanish;
					(item as any).part_description_en = partData.description_english;
				}
			} catch (error) {
				console.error('Error loading part data:', error);
			}
		}

		// Load unit of measure data
		if (item.unit_of_measure) {
			try {
				const response = await fetch(`/api-sveltekit/units-of-measure/${item.unit_of_measure}`, {
					method: 'GET',
					headers: { 'Content-Type': 'application/json' }
				});
				if (response.ok) {
					const unitData = await response.json();
					(item as any).unit_code = unitData.code;
					(item as any).unit_description = unitData.description || unitData.description_en;
				}
			} catch (error) {
				console.error('Error loading unit data:', error);
			}
		}

		// Load country data (if needed)
		if (item.customs?.origin_country) {
			try {
				const response = await fetch(
					`/api-sveltekit/countries?search=${item.customs.origin_country}`,
					{ method: 'GET', headers: { 'Content-Type': 'application/json' } }
				);
				if (response.ok) {
					const data = await response.json();
					if (data.items && data.items.length > 0) {
						const country = data.items[0];
						(item.customs as any).origin_country_name =
							country.description || country.description_en;
					}
				}
			} catch (error) {
				console.error('Error loading country data:', error);
			}
		}

		// Load fraction data (if needed)
		if (item.customs?.fraction) {
			try {
				const response = await fetch(
					`/api-sveltekit/tariff-fractions?search=${item.customs.fraction}`,
					{ method: 'GET', headers: { 'Content-Type': 'application/json' } }
				);
				if (response.ok) {
					const data = await response.json();
					if (data.items && data.items.length > 0) {
						const fraction = data.items[0];
						(item.customs as any).fraction_description = fraction.description;
					}
				}
			} catch (error) {
				console.error('Error loading fraction data:', error);
			}
		}

		// Load package data (if needed)
		const packageId = item.quantity?.package_id;
		if (packageId && item.quantity) {
			try {
				const response = await fetch('/api-sveltekit/packages', {
					method: 'GET',
					headers: { 'Content-Type': 'application/json' }
				});
				if (response.ok) {
					const data = await response.json();
					const packages = data.items || data.data || data;
					if (Array.isArray(packages)) {
						const pkg = packages.find((p: any) => p.id === packageId);
						if (pkg) {
							(item.quantity as any).package_description =
								pkg.description_es || pkg.description_en || pkg.key;
							(item.quantity as any).package_key = pkg.key;
							(item.quantity as any).package_weight_unit = pkg.weight_unit || 0;
						}
					}
				}
			} catch (error) {
				console.error('Error loading package data:', error);
			}
		}

		// Load payment method description (if needed)
		if (item.payment_method) {
			try {
				const response = await fetch('/api-sveltekit/payment-methods', {
					method: 'GET',
					headers: { 'Content-Type': 'application/json' }
				});
				if (response.ok) {
					const data = await response.json();
					const methods = data.items || data.data || data;
					if (Array.isArray(methods)) {
						const method = methods.find((m: any) => m.key === item.payment_method);
						if (method) {
							(item as any).payment_method_description = method.description;
						}
					}
				}
			} catch (error) {
				console.error('Error loading payment method data:', error);
			}
		}
	}

	// Normalize numeric values from strings to numbers
	function normalizeItemData(item: Partial<Item>): Partial<Item> {
		if (item) {
			const normalizedItem = { ...item };

			// Normalize financials
			if (normalizedItem.financial) {
				normalizedItem.financial = {
					...normalizedItem.financial,
					unit_cost_usd:
						normalizedItem.financial.unit_cost_usd != null
							? Number(normalizedItem.financial.unit_cost_usd)
							: undefined,
					unit_cost_mxn:
						normalizedItem.financial.unit_cost_mxn != null
							? Number(normalizedItem.financial.unit_cost_mxn)
							: undefined,
					value_usd:
						normalizedItem.financial.value_usd != null
							? Number(normalizedItem.financial.value_usd)
							: undefined,
					value_mxn:
						normalizedItem.financial.value_mxn != null
							? Number(normalizedItem.financial.value_mxn)
							: undefined
				};
			}

			// Normalize quantities
			if (normalizedItem.quantity) {
				normalizedItem.quantity = {
					...normalizedItem.quantity,
					quantity:
						normalizedItem.quantity.quantity != null
							? Number(normalizedItem.quantity.quantity)
							: undefined,
					net_weight:
						normalizedItem.quantity.net_weight != null
							? Number(normalizedItem.quantity.net_weight)
							: undefined,
					gross_weight:
						normalizedItem.quantity.gross_weight != null
							? Number(normalizedItem.quantity.gross_weight)
							: undefined,
					package_quantity:
						normalizedItem.quantity.package_quantity != null
							? Number(normalizedItem.quantity.package_quantity)
							: undefined
				};
			}

			return normalizedItem;
		}

		return item;
	}

	function handleDelete(lineData: any) {
		selectedItem = lineData.full_item;
		showDeleteDialog = true;
	}

	async function saveNewItem() {
		if (!invoice?.id || !activeCompanyId) return;

		isSaving = true;
		try {
			// Clean item data before sending
			const cleanedItem = cleanLineData(editingItem);

			const response = await itemsApi.create(activeCompanyId, {
				...cleanedItem,
				invoice_id: invoice.id
			});

			// Verificar si hay errores de validación
			if ('error' in response) {
				// Manejar errores de validación (422)
				if (response.validationErrors && Array.isArray(response.validationErrors)) {
					const validationErrors = response.validationErrors
						.map((err: any) => `• ${err.message}`)
						.join('\n');

					toast.error('Errores de validación', {
						description: validationErrors,
						duration: 10000
					});
				} else {
					toast.error('Error al crear item', {
						description: response.error || 'No se pudo crear el item. Intenta de nuevo.'
					});
				}
				isSaving = false;
				return;
			}

			// Recargar items
			await loadItems();

			showItemSheet = false;
			toast.success('Item creado', {
				description: 'El item se ha creado correctamente.'
			});
		} catch (error: any) {
			console.error('Error creating item:', error);

			// Manejar errores de validación (422)
			if (error?.response?.data?.errors && Array.isArray(error.response.data.errors)) {
				const validationErrors = error.response.data.errors
					.map((err: any) => `• ${err.message}`)
					.join('\n');

				toast.error('Errores de validación', {
					description: validationErrors
				});
			} else {
				const errorMessage =
					error?.response?.data?.detail || 'No se pudo crear el item. Intenta de nuevo.';
				toast.error('Error al crear item', {
					description: errorMessage
				});
			}
		} finally {
			isSaving = false;
		}
	}

	async function saveEditedItem() {
		if (!selectedItem?.id || !activeCompanyId) return;

		isSaving = true;
		try {
			// Clean item data before sending
			const cleanedItem = cleanLineData(editingItem);

			const response = await itemsApi.update(selectedItem.id, activeCompanyId, cleanedItem);

			// Verificar si hay errores de validación
			if ('error' in response) {
				// Manejar errores de validación (422)
				if (response.validationErrors && Array.isArray(response.validationErrors)) {
					const validationErrors = response.validationErrors
						.map((err: any) => `• ${err.message}`)
						.join('\n');

					toast.error('Errores de validación', {
						description: validationErrors,
						duration: 10000
					});
				} else {
					toast.error('Error al actualizar item', {
						description: response.error || 'No se pudo actualizar el item. Intenta de nuevo.'
					});
				}
				isSaving = false;
				return;
			}

			// Recargar items
			await loadItems();

			showItemSheet = false;
			toast.success('Item actualizado', {
				description: 'El item se ha actualizado correctamente.'
			});
		} catch (error: any) {
			console.error('Error updating item:', error);

			// Manejar errores de validación (422)
			if (error?.response?.data?.errors && Array.isArray(error.response.data.errors)) {
				const validationErrors = error.response.data.errors
					.map((err: any) => `• ${err.message}`)
					.join('\n');

				toast.error('Errores de validación', {
					description: validationErrors
				});
			} else {
				const errorMessage =
					error?.response?.data?.detail || 'No se pudo actualizar el item. Intenta de nuevo.';
				toast.error('Error al actualizar item', {
					description: errorMessage
				});
			}
		} finally {
			isSaving = false;
		}
	}

	function saveItem() {
		// Validar campos obligatorios antes de guardar
		const missingFields: string[] = [];

		if (!editingItem) {
			toast.warning('Error de datos', {
				description: 'No se encontró información del item'
			});
			return;
		}

		// 1. Clase
		if (!editingItem.class_id) {
			missingFields.push('Clase');
		}

		// 2. Cantidad
		if (!editingItem.quantity?.quantity || editingItem.quantity.quantity <= 0) {
			missingFields.push('Cantidad');
		}

		// 3. Unidad de Medida
		if (!editingItem.unit_of_measure) {
			missingFields.push('U.M. (Unidad de Medida)');
		}

		// 4. Costo Unitario (al menos uno debe estar presente)
		const hasCost =
			editingItem.financial?.unit_cost_usd ||
			editingItem.financial?.unit_cost_mxn ||
			editingItem.financial?.unit_cost_capture;
		if (!hasCost) {
			missingFields.push('Costo Unitario (USD, MXN o Captura)');
		}

		// 5. País de Origen
		if (!editingItem.customs?.origin_country) {
			missingFields.push('País de Origen');
		}

		// 6. Tipo de Tarifa
		if (!editingItem.customs?.fraction_type) {
			missingFields.push('Tipo de Tarifa');
		}

		// 7. Descripción en Español
		if (!editingItem.description?.description_spanish?.trim()) {
			missingFields.push('Descripción en Español');
		}

		if (missingFields.length > 0) {
			const fieldsList = missingFields.join('\n• ');
			toast.warning('Completa los campos obligatorios', {
				description: `Faltan los siguientes campos:\n• ${fieldsList}`,
				duration: 10000
			});
			return;
		}

		// Si pasa la validación, continuar con el guardado
		if (isTargetingPreset) {
			saveItemToPreset();
		} else if (isEditMode) {
			saveEditedItem();
		} else {
			saveNewItem();
		}
	}

	async function confirmDelete() {
		if (!selectedItem?.id || !activeCompanyId) return;

		isSaving = true;
		try {
			await itemsApi.delete(selectedItem.id, activeCompanyId);

			// Recargar items
			await loadItems();

			showDeleteDialog = false;
			toast.success('Item eliminado', {
				description: 'El item se ha eliminado correctamente.'
			});
		} catch (error: any) {
			console.error('Error deleting item:', error);
			const errorMessage =
				error?.response?.data?.detail || 'No se pudo eliminar el item. Intenta de nuevo.';
			toast.error('Error al eliminar item', {
				description: errorMessage
			});
		} finally {
			isSaving = false;
		}
	}

	function handleCancelEdit() {
		// Restaurar los datos originales si estamos editando
		if (isEditMode && originalItemData) {
			editingItem = JSON.parse(JSON.stringify(originalItemData));
		}
		// Cerrar el sheet
		showItemSheet = false;
	}
</script>

<div class="grid grid-cols-4 grid-rows-1 gap-3">
	<div class="col-span-3 space-y-3 rounded-md border p-3">
		<div class="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
			<div>
				<h3 class="text-sm font-semibold">Items de la Factura</h3>
				<p class="text-xs text-muted-foreground">
					Carga partidas, crea o aplica plantillas sin salir de esta vista.
				</p>
			</div>
			<div class="flex flex-wrap justify-end gap-2">
				<Button
					size="sm"
					variant="secondary"
					class="shadow-sm"
					onclick={openUsePresetDialog}
					type="button"
				>
					<Sparkles class="mr-1 h-4 w-4" />
					Usar plantilla
				</Button>
				<Button size="sm" variant="outline" onclick={openCreatePresetDialog} type="button">
					<Plus class="mr-1 h-4 w-4" />
					Crear plantilla
				</Button>
				<Button size="sm" onclick={handleAdd} type="button">
					<Plus class="mr-1 h-4 w-4" />
					Agregar Item
				</Button>
			</div>
		</div>

		<div
			bind:this={tableContainer}
			onscroll={handleScroll}
			class="max-h-[500px] overflow-auto rounded-md border"
		>
			<Table.Root>
				<Table.Header class="bg-background">
					<Table.Row>
						<Table.Head>Línea</Table.Head>
						<Table.Head>P/S</Table.Head>
						<Table.Head>Clase</Table.Head>
						<Table.Head>Descripcion Clase</Table.Head>
						<Table.Head>Cant. Importada</Table.Head>
						<Table.Head>U.M.</Table.Head>
						<Table.Head>Preferencia</Table.Head>
						<Table.Head>Contiene Subpartida</Table.Head>
						<Table.Head>Partida Principal</Table.Head>
						<Table.Head class="w-[120px] text-right">Acciones</Table.Head>
					</Table.Row>
				</Table.Header>
				<Table.Body>
					{#if displayedItems.length === 0}
						<Table.Row>
							<Table.Cell
								colspan={operationType === 1 ? 11 : 10}
								class="py-8 text-center text-muted-foreground"
							>
								No hay items disponibles
							</Table.Cell>
						</Table.Row>
					{:else}
						{#each displayedItems as item (item.id)}
							<Table.Row
								onclick={() => handleRowClick(item)}
								class="cursor-pointer transition-colors hover:bg-muted/50 {focusedLine?.id ===
								item.id
									? 'bg-muted ring-1 ring-primary/20 ring-inset'
									: ''}"
							>
								{#if operationType === 1}
									<Table.Cell>{item.line_number}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_invoice || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_line || '-'}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.part_number_display || '-'}</Table.Cell>
									<Table.Cell
										class="max-w-[200px] truncate"
										title={item.description?.description_spanish}
									>
										{item.description?.description_spanish || '-'}
									</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? 'Sí' : 'No'}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{:else if invoiceType === 'CR'}
									<Table.Cell>{item.line_number}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_invoice || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_line || '-'}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.part_number_display || '-'}</Table.Cell>
									<Table.Cell
										class="max-w-[200px] truncate"
										title={item.description?.description_spanish}
									>
										{item.description?.description_spanish || '-'}
									</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? 'Sí' : 'No'}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{:else if invoiceType === 'REP' || invoiceType === 'REPAR'}
									<Table.Cell>{item.line_number}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_invoice || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_line || '-'}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.part_number_display || '-'}</Table.Cell>
									<Table.Cell
										class="max-w-[200px] truncate"
										title={item.description?.description_spanish}
									>
										{item.description?.description_spanish || '-'}
									</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.unit_of_measure_code || '-'}</Table.Cell>
									<Table.Cell>{item.reference_number || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? 'Sí' : 'No'}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{:else}
									<Table.Cell>{item.line_number}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.class_description || '-'}</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.unit_of_measure_code || '-'}</Table.Cell>
									<Table.Cell>{item.reference_number || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? 'Sí' : 'No'}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{/if}
								<Table.Cell class="text-right">
									<div class="flex justify-end gap-2">
										<Button size="icon" variant="ghost" onclick={() => handleEdit(item)}>
											<Pencil class="h-4 w-4" />
										</Button>
										<Button size="icon" variant="ghost" onclick={() => handleDelete(item)}>
											<Trash2 class="h-4 w-4 text-destructive" />
										</Button>
									</div>
								</Table.Cell>
							</Table.Row>
						{/each}
						{#if isLoadingMore}
							<Table.Row>
								<Table.Cell colspan={operationType === 1 ? 11 : 10} class="py-4 text-center">
									<span class="text-sm text-muted-foreground">Cargando más items...</span>
								</Table.Cell>
							</Table.Row>
						{/if}
					{/if}
				</Table.Body>
			</Table.Root>
		</div>

		{#if flattenedLines.length > 0}
			<div class="text-right text-xs text-muted-foreground">
				Mostrando {displayedItems.length} de {flattenedLines.length} líneas
			</div>
		{/if}
	</div>

	<div class="col-start-4 space-y-4">
		{#if operationType === 1}
			<!-- Top Box: Descripción en español -->
			<div class="flex h-[200px] flex-col rounded-md border p-3">
				<h4 class="mb-2 text-xs font-semibold text-muted-foreground uppercase">
					Descripción en español:
				</h4>
				<div class="flex-1 overflow-auto rounded border bg-muted/30 p-2">
					{#if focusedLine}
						<p class="text-xs leading-relaxed font-medium">
							{focusedLine.description?.description_spanish || 'Sin descripción disponible.'}
						</p>
					{:else}
						<p class="flex h-full items-center justify-center text-xs text-muted-foreground italic">
							Selecciona una fila para ver la descripción.
						</p>
					{/if}
				</div>
			</div>
		{/if}

		<!-- Bottom Box (or only box in Import): Quantities and Values -->
		<div class="space-y-3 rounded-md border p-3">
			<div>
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">Cantidades:</h4>
				<div>
					<div class="grid grid-cols-2 gap-3">
						<div>
							Partidas: <span class="text-blue-400">{items.length || 0}</span>
						</div>
						<div>
							Bultos: <span class="text-blue-400">0</span>
						</div>
					</div>
				</div>
				Importada:<span class="text-blue-400">{imported || 0}</span> <br />
				Peso neto: <span class="text-blue-400">{net_weight || 0}</span><br />
				Peso bruto: <span class="text-blue-400">{gross_weight || 0}</span> <br />
			</div>

			<h4 class="col-span-2 text-xs font-semibold text-muted-foreground uppercase">
				Valores de importacion:
			</h4>
			Dolares:<span class="text-blue-400">0</span> <span class="text-red-400">USD</span> <br />
			Pesos: <span class="text-blue-400">0</span> <span class="text-red-400">MXN</span><br />
			De Captura: <span class="text-blue-400">0</span> <span class="text-red-400">USD</span>

			<h4 class="col-span-2 text-xs font-semibold text-muted-foreground uppercase opacity-0">
				spacer
			</h4>

			Aduana:<span class="text-blue-400">0</span> <span class="text-red-400">USD</span><br />
			Aduana: <span class="text-blue-400">0</span> <span class="text-red-400">MXN</span><br />
		</div>
	</div>
</div>

<!-- Delete Confirmation Dialog -->
<Dialog.Root bind:open={showDeleteDialog}>
	<Dialog.Content class="[&>button]:hidden">
		<Dialog.Header>
			<Dialog.Title>Confirmar Eliminación</Dialog.Title>
			<Dialog.Description>
				¿Está seguro que desea eliminar este item? Esta acción no se puede deshacer.
			</Dialog.Description>
		</Dialog.Header>
		<Dialog.Footer>
			<Button
				variant="outline"
				onclick={() => (showDeleteDialog = false)}
				disabled={isSaving}
				type="button"
			>
				Cancelar
			</Button>
			<Button variant="destructive" onclick={confirmDelete} disabled={isSaving} type="button">
				{#if isSaving}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Eliminando...
				{:else}
					Eliminar
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Preset dialogs -->
<Dialog.Root
	bind:open={showUsePresetDialog}
	onOpenChange={(open) => {
		if (!open) {
			showUsePresetDialog = false;
			selectedPreset = null;
		}
	}}
>
	<Dialog.Content
		class="flex h-[85vh] flex-col gap-0 overflow-hidden p-0 sm:max-w-7xl [&>button]:hidden"
	>
		<!-- Fixed Header -->
		<div class="z-20 flex items-center justify-between border-b bg-background px-6 py-4">
			<div>
				<Dialog.Title>Usar plantilla</Dialog.Title>
				<Dialog.Description>
					Selecciona una plantilla predefinida para cargar sus partidas.
				</Dialog.Description>
			</div>
			<div class="flex items-center gap-2">
				<Button
					variant="ghost"
					size="sm"
					onclick={() => loadPresets(true)}
					disabled={isLoadingPresets}
					class="h-8 text-muted-foreground"
				>
					<Loader2 class={`mr-2 h-3.5 w-3.5 ${isLoadingPresets ? 'animate-spin' : ''}`} />
					Actualizar
				</Button>
				<Button
					variant="ghost"
					size="icon"
					onclick={() => (showUsePresetDialog = false)}
					class="h-8 w-8 text-muted-foreground"
				>
					<X class="h-4 w-4" />
				</Button>
			</div>
		</div>

		<!-- Main Content Area (Split View) -->
		<div class="flex flex-1 overflow-hidden">
			<!-- Sidebar: List -->
			<div class="flex w-[340px] flex-col border-r bg-muted/30">
				<div
					class="border-b bg-background/50 p-4 backdrop-blur supports-[backdrop-filter]:bg-background/50"
				>
					<div class="relative">
						<Search
							class="absolute top-1/2 left-2.5 h-4 w-4 -translate-y-1/2 text-muted-foreground"
						/>
						<Input
							placeholder="Buscar plantillas..."
							class="h-9 bg-background pl-9"
							bind:value={searchPresets}
						/>
					</div>
				</div>

				<div class="flex-1 overflow-y-auto">
					{#if isLoadingPresets}
						<div
							class="flex flex-col items-center justify-center gap-3 py-12 text-muted-foreground"
						>
							<Loader2 class="h-8 w-8 animate-spin text-primary/20" />
							<span class="text-xs font-medium">Cargando...</span>
						</div>
					{:else if filteredPresets.length === 0}
						<div
							class="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center text-muted-foreground"
						>
							<PackageOpen class="h-10 w-10 opacity-20" />
							<p class="text-sm">No se encontraron plantillas</p>
						</div>
					{:else}
						{#each filteredPresets as preset}
							<button
								type="button"
								class={`group relative w-full border-b p-4 text-left transition-all hover:bg-muted/50 ${selectedPreset?.id === preset.id ? 'z-10 bg-background' : 'text-muted-foreground'}`}
								onclick={() => (selectedPreset = preset)}
							>
								{#if selectedPreset?.id === preset.id}
									<div class="absolute top-0 bottom-0 left-0 w-[3px] bg-primary"></div>
								{/if}
								<div class="space-y-1.5">
									<div class="flex items-start justify-between gap-2">
										<span
											class={`line-clamp-1 text-sm font-medium ${selectedPreset?.id === preset.id ? 'text-foreground' : ''}`}
											>{preset.name}</span
										>
										{#if preset.items?.length}
											<Badge
												variant="secondary"
												class="h-5 shrink-0 px-1.5 text-[10px] tabular-nums"
												>{preset.items.length}</Badge
											>
										{/if}
									</div>
									<p class="line-clamp-2 text-xs leading-relaxed opacity-80">
										{preset.description || 'Sin descripción'}
									</p>
									<div class="flex items-center pt-1 text-[10px] opacity-60">
										<Calendar class="mr-1 h-3 w-3" />
										{preset.created_at ? new Date(preset.created_at).toLocaleDateString() : 'N/A'}
									</div>
								</div>
							</button>
						{/each}
					{/if}
				</div>
			</div>

			<!-- Main Panel: Preview -->
			<div class="flex flex-1 flex-col overflow-hidden bg-slate-50/50 dark:bg-slate-900/50">
				{#if !selectedPreset}
					<div
						class="flex flex-1 flex-col items-center justify-center space-y-4 text-muted-foreground/50"
					>
						<div class="flex h-16 w-16 items-center justify-center rounded-full bg-muted/50">
							<LayoutTemplate class="h-8 w-8" />
						</div>
						<p class="font-medium">Selecciona una plantilla para ver sus detalles</p>
					</div>
				{:else}
					<div class="flex h-full flex-col">
						<!-- Preview Header -->
						<div class="flex shrink-0 items-start justify-between border-b bg-background px-6 py-5">
							<div class="space-y-1">
								<h3 class="flex items-center gap-2 text-lg font-semibold">
									{selectedPreset.name}
								</h3>
								<p class="max-w-2xl text-sm leading-relaxed text-muted-foreground">
									{selectedPreset.description || 'Sin descripción disponible.'}
								</p>
							</div>
							<div class="ml-4 shrink-0 text-right">
								<div class="text-xs font-medium tracking-wider text-muted-foreground uppercase">
									Creada
								</div>
								<div class="text-sm font-medium tabular-nums">
									{selectedPreset.created_at
										? new Date(selectedPreset.created_at).toLocaleDateString(undefined, {
												dateStyle: 'long'
											})
										: '-'}
								</div>
							</div>
						</div>

						<!-- Preview Table -->
						<div class="relative flex-1 overflow-auto bg-background/50">
							<Table.Root>
								<Table.Header class="sticky top-0 z-10 bg-background shadow-sm">
									<Table.Row class="border-b hover:bg-transparent">
										<Table.Head class="h-10 w-12 bg-muted/10 text-center">#</Table.Head>
										<Table.Head class="h-10 bg-muted/10">Descripción del Item</Table.Head>
										<Table.Head class="h-10 w-24 bg-muted/10 text-center">Cant.</Table.Head>
										<Table.Head class="h-10 w-32 bg-muted/10 text-right">Costo (USD)</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#if selectedPresetItems.length === 0}
										<Table.Row>
											<Table.Cell colspan={4} class="h-40 text-center text-muted-foreground">
												<div class="flex flex-col items-center gap-2">
													<PackageOpen class="h-8 w-8 opacity-20" />
													<span>Esta plantilla no contiene items.</span>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										{#each selectedPresetItems as item, i}
											<Table.Row class="border-b-muted/40 hover:bg-muted/40">
												<Table.Cell
													class="border-r-muted/20 text-center font-mono text-xs text-muted-foreground"
												>
													{i + 1}
												</Table.Cell>
												<Table.Cell>
													<div class="flex flex-col py-0.5">
														<span class="text-sm font-medium text-foreground/90">
															{item?.description?.description_spanish || 'Sin descripción'}
														</span>
														{#if item.reference_number}
															<span class="mt-0.5 font-mono text-[10px] text-muted-foreground/70">
																REF: {item.reference_number}
															</span>
														{/if}
													</div>
												</Table.Cell>
												<Table.Cell class="text-center font-medium tabular-nums">
													{item?.quantity?.quantity || 0}
												</Table.Cell>
												<Table.Cell class="text-right text-muted-foreground tabular-nums">
													${(item?.financial?.unit_cost_usd || 0).toLocaleString(undefined, {
														minimumFractionDigits: 2
													})}
												</Table.Cell>
											</Table.Row>
										{/each}
									{/if}
								</Table.Body>
							</Table.Root>
						</div>
					</div>
				{/if}
			</div>
		</div>

		<!-- Sticky Footer -->
		<div class="z-20 flex shrink-0 justify-end gap-3 border-t bg-background px-6 py-4">
			<Button variant="outline" onclick={() => (showUsePresetDialog = false)} type="button">
				Cancelar
			</Button>
			<Button
				onclick={applySelectedPreset}
				disabled={!selectedPreset || selectedPresetCount === 0 || isApplyingPreset}
				class="min-w-[160px] bg-primary text-primary-foreground shadow-sm hover:bg-primary/90"
			>
				{#if isApplyingPreset}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Aplicando...
				{:else}
					<Sparkles class="mr-2 h-4 w-4" />
					Aplicar Plantilla
				{/if}
			</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>

<Dialog.Root
	bind:open={showCreatePresetDialog}
	onOpenChange={(open) => {
		if (!open) {
			createPresetName = '';
			createPresetDescription = '';
		}
	}}
>
	<Dialog.Content class="sm:max-w-4xl [&>button]:hidden">
		<Dialog.Header>
			<Dialog.Title>Crear plantilla</Dialog.Title>
			<Dialog.Description
				>Guarda los elementos actuales como una plantilla reutilizable para inyectar en otras
				partidas.</Dialog.Description
			>
		</Dialog.Header>

		<div class="space-y-4">
			<div class="grid gap-3 md:grid-cols-2">
				<div class="space-y-2">
					<label for="preset-name" class="text-sm font-medium">Nombre de la Plantilla</label>
					<Input
						id="preset-name"
						placeholder="Ej. Paquete estándar de refacciones"
						bind:value={createPresetName}
					/>
				</div>
				<div class="space-y-2">
					<label for="preset-description" class="text-sm font-medium">Descripción</label>
					<Textarea
						id="preset-description"
						rows={2}
						placeholder="Indica para qué sirve esta plantilla..."
						bind:value={createPresetDescription}
					/>
				</div>
			</div>

			<div class="flex items-center justify-end">
				<div class="mr-auto text-sm text-muted-foreground">
					<Badge variant="secondary">{builderItems.length} items/líneas</Badge>
				</div>
			</div>

			<div class="max-h-[50vh] overflow-hidden overflow-y-auto rounded-md border">
				<div class="flex items-center justify-between border-b bg-muted/30 p-2">
					<span class="text-xs font-medium tracking-wider text-muted-foreground uppercase"
						>Items de la plantilla</span
					>
					<Button size="sm" variant="outline" class="h-7 text-xs" onclick={handleAdd}>
						<Plus class="mr-1 h-3.5 w-3.5" /> Agregar Item/Línea
					</Button>
				</div>

				<Table.Root>
					<Table.Header>
						<Table.Row>
							<Table.Head class="w-10 text-center">#</Table.Head>
							<Table.Head>Descripción</Table.Head>
							<Table.Head class="text-center">Cant.</Table.Head>
							<Table.Head class="pr-4 text-right">Acciones</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if builderItems.length === 0}
							<Table.Row>
								<Table.Cell
									colspan={4}
									class="py-8 text-center text-sm text-muted-foreground italic"
								>
									Usa el botón "Agregar Item/Línea" para definir el contenido de la plantilla.
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each builderItems as item, i}
								<Table.Row>
									<Table.Cell class="text-center font-mono text-xs text-muted-foreground">
										{i + 1}
									</Table.Cell>
									<Table.Cell>
										<div class="flex flex-col">
											<span class="text-sm font-medium">
												{item?.[0]?.description?.description_spanish || 'Sin descripción'}
											</span>
											<span class="text-[10px] text-muted-foreground"
												>Ref: {item.reference_number || '-'}</span
											>
										</div>
									</Table.Cell>
									<Table.Cell class="text-center text-sm">
										{item?.[0]?.quantity?.quantity || 0}
									</Table.Cell>
									<Table.Cell class="pr-2 text-right">
										<div class="flex justify-end gap-1">
											<Button
												size="icon"
												variant="ghost"
												class="h-7 w-7"
												onclick={() => handleEditInPreset(i)}
											>
												<Pencil class="h-3.5 w-3.5" />
											</Button>
											<Button
												size="icon"
												variant="ghost"
												class="h-7 w-7 text-destructive"
												onclick={() => handleRemoveFromPreset(i)}
											>
												<Trash2 class="h-3.5 w-3.5" />
											</Button>
										</div>
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
					</Table.Body>
				</Table.Root>
			</div>

			<div class="flex justify-end gap-2">
				<Button variant="outline" onclick={() => (showCreatePresetDialog = false)} type="button"
					>Cancelar</Button
				>
				<Button
					onclick={saveCurrentItemsAsPreset}
					disabled={isSavingPreset || builderItems.length === 0}
					class="bg-emerald-600 text-white hover:bg-emerald-700"
					type="button"
				>
					{#if isSavingPreset}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						Guardando...
					{:else}
						<SaveIcon class="mr-2 h-4 w-4" />
						Guardar plantilla
					{/if}
				</Button>
			</div>
		</div>
	</Dialog.Content>
</Dialog.Root>

<!-- Item Sheet (Panel lateral para agregar/editar) -->
<!-- Renderizar el componente apropiado según el sistema -->
{#if invoiceSystem === 'fixed_asset'}
	<ItemSheetFa
		bind:open={showItemSheet}
		{isEditMode}
		bind:editingItem
		{invoice}
		{isTargetingPreset}
		onSave={saveItem}
		onCancel={() => {
			showItemSheet = false;
		}}
		{isSaving}
	/>
{:else}
	<ItemSheetInv
		bind:open={showItemSheet}
		{isEditMode}
		bind:editingItem
		{invoice}
		{isTargetingPreset}
		onSave={saveItem}
		onCancel={() => {
			showItemSheet = false;
		}}
		{isSaving}
	/>
{/if}
