<script lang="ts">
	import { tick } from 'svelte';
	import { browser } from '$app/environment';
	import * as Sheet from '$lib/components/ui/sheet';
	import * as Tabs from '$lib/components/ui/tabs';
	import { Input } from '$lib/components/ui/input';
	import { Textarea } from '$lib/components/ui/textarea';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import { Badge } from '$lib/components/ui/badge';
	import { Loader2, FileText, Folder, AlertCircle, X } from 'lucide-svelte';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import type { Item } from '$lib/api/dashboard/a76/items';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosPestanasItemInv } from '$lib/config/shortcuts/dashboard/invoices/item/inventory';
	import PartNumberDialog from '../fa/part-number-dialog.svelte';
	import ClassDialog from '../fa/class-dialog.svelte';
	import UnitOfMeasureDialog from '../fa/unit-of-measure-dialog.svelte';
	import CountryDialog from '../fa/country-dialog.svelte';
	import TariffFractionDialog from '../fa/tariff-fraction-dialog.svelte';
	import {
		buildMexTariffDigitsFromCatalogRow,
		formatMexTariffDigitsForDisplay,
		normalizeMexTariffDigitsStored
	} from '$lib/utils/mexican-tariff-fraction';
	import { m } from '$lib/i18n/messages';

	let {
		open = $bindable(),
		isEditMode = false,
		editingItem = $bindable(),
		invoice,
		onSave,
		onCancel,

		isTargetingPreset = false,
		isSaving = false
	}: {
		open: boolean;
		isEditMode?: boolean;
		editingItem: Partial<Item>;
		invoice: Invoice | null;
		onSave: () => void;
		onCancel?: () => void;

		isTargetingPreset?: boolean;
		isSaving?: boolean;
		saveError?: { field: string; message: string }[] | null;
		onDismissSaveError?: () => void;
	} = $props();

	let activeTab = $state('general');
	let showPartDialog = $state(false);
	let showClassDialog = $state(false);
	let showUnitDialog = $state(false);
	let showCountryDialog = $state(false);
	let showFractionDialog = $state(false);

	const tabMapping: Record<string, string> = {
		tab1: 'general',
		tab2: 'clasificacion',
		tab3: 'cantidades',
		tab4: 'otros'
	};

	function openOnEnterOrSpace(event: KeyboardEvent, action: () => void) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			action();
		}
	}

	function handlePartSelect(part: any) {
		editingItem.part_number_id = part.id;
		editingItem.part_number = part.part_number;
		// Store part number for display
		(editingItem as any).part_number_display = part.part_number;
		if (editingItem.description) {
			if (part.description_spanish) editingItem.description.description_spanish = part.description_spanish;
			if (part.description_english) editingItem.description.description_english = part.description_english;
		}
		if (editingItem.customs) {
			editingItem.customs.fraction = normalizeMexTariffDigitsStored(part.fraction);
		}
		if (!editingItem.fda_key && part.fda_key) {
			editingItem.fda_key = part.fda_key;
		}
		if (!editingItem.fcc_key && part.fcc_key) {
			editingItem.fcc_key = part.fcc_key;
		}
	}

	function handleClassSelect(classItem: any) {
		editingItem.class_id = classItem.id;
		(editingItem as any).class_code = classItem.class_code;
		(editingItem as any).class_description = classItem.description_es || classItem.description_en;
		if (editingItem.description) {
			if (classItem.description_es) editingItem.description.description_spanish = classItem.description_es;
			if (classItem.description_en) editingItem.description.description_english = classItem.description_en;
		}
	}

	function handleUnitSelect(unit: any) {
		editingItem.unit_of_measure = unit.id;
		(editingItem as any).unit_code = unit.code;
		(editingItem as any).unit_description = unit.description || unit.description_en;
		if (editingItem.quantity) {
			editingItem.quantity.unit_of_measure = unit.code;
		}
	}

	function handleCountrySelect(country: any) {
		if (!editingItem.customs) editingItem.customs = {} as any;
		if (editingItem.customs) {
			editingItem.customs.origin_country = country.m3_key || country.mex_key;
			(editingItem.customs as any).origin_country_name = country.description_es || country.description_en;
		}
	}

	function handleFractionSelect(fraction: any) {
		if (!editingItem.customs) editingItem.customs = {} as any;
		editingItem.customs.fraction = buildMexTariffDigitsFromCatalogRow(fraction);
		(editingItem.customs as any).fraction_description = fraction.description;
	}

	const fractionDisplay = $derived(
		formatMexTariffDigitsForDisplay(editingItem.customs?.fraction ?? '')
	);

	const systemLabel = $derived.by(() => {
		switch ((invoice?.system || '').toLowerCase()) {
			case 'fixed_asset':
				return 'SCAF (Activo Fijo)';
			case 'csv':
				return 'CSV';
			case 'scaii':
				return 'SCAII (Inventario)';
			default:
				return invoice?.system || 'Inventario';
		}
	});

	useShortcuts(
		'Invoice Item Form (Inventory)',
		obtenerAtajosPestanasItemInv({
			cambiarPestana: (target) => {
				const tab = tabMapping[target];
				if (tab) activeTab = tab;
			},
			manejarGuardar: onSave,
			manejarCancelar: () => onCancel?.()
		})
	);

	let previousSheetOpenInv = $state(false);
	$effect(() => {
		if (!browser) return;
		if (open && !previousSheetOpenInv) {
			void tick().then(() => {
				const root = document.querySelector('[data-invoice-item-sheet="inventory"]');
				const first = root?.querySelector<HTMLElement>(
					'input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled])'
				);
				first?.focus();
			});
		}
		previousSheetOpenInv = open;
	});

	// Use editingItem directly and ensure it's safe
	$effect(() => {
		if (open && editingItem) {
			if (!editingItem.quantity) editingItem.quantity = {} as any;
			if (!editingItem.financial) editingItem.financial = {} as any;
			if (!editingItem.customs) editingItem.customs = {} as any;
			if (!editingItem.description) editingItem.description = {} as any;
			if (editingItem.has_fda_code === undefined) editingItem.has_fda_code = false;
		}
	});
</script>

<PartNumberDialog bind:open={showPartDialog} onSelect={handlePartSelect} />
<ClassDialog bind:open={showClassDialog} onSelect={handleClassSelect} />
<UnitOfMeasureDialog bind:open={showUnitDialog} onSelect={handleUnitSelect} />
<CountryDialog bind:open={showCountryDialog} onSelect={handleCountrySelect} />
<TariffFractionDialog bind:open={showFractionDialog} onSelect={handleFractionSelect} />

<Sheet.Root bind:open>
	<Sheet.Content
		side="right"
		class="w-[50vw] overflow-hidden p-0 sm:max-w-none"
		data-invoice-item-sheet="inventory"
	>
		<div
			class="flex items-start justify-between gap-3 border-b bg-white px-6 py-4 dark:bg-zinc-950"
			role="toolbar"
			aria-label={m.invoice_item_inv.edit_title()}
		>
			<div class="space-y-1">
				<Sheet.Title class="text-lg font-semibold">
					{isEditMode ? m.invoice_item_inv.edit_title() : m.invoice_item_inv.add_title()} - {systemLabel}
				</Sheet.Title>
				<Sheet.Description class="text-sm text-muted-foreground">
					{isEditMode ? m.invoice_item_inv.edit_description() : m.invoice_item_inv.add_description()}
					{#if editingItem}
						<Badge variant="secondary" class="ml-2">
							{m.invoice_item_inv.line_prefix()} {editingItem.line_number || 1}
						</Badge>
					{/if}
				</Sheet.Description>
			</div>
			<div class="flex gap-2">
				<Button variant="outline" onclick={() => onCancel?.()} disabled={isSaving}>{m.invoice_item_inv.cancel()}</Button>
				<Button onclick={onSave} disabled={isSaving}>
					{#if isSaving}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						{m.invoice_item_inv.saving()}
					{:else}
						{isEditMode ? m.invoice_item_inv.update() : m.invoice_item_inv.create()}
					{/if}
				</Button>
		</div>
	</div>

	{#if saveError?.length}
		<div class="flex items-start gap-2 border-b border-destructive/20 bg-destructive/5 px-4 py-2">
			<AlertCircle class="mt-0.5 size-3.5 shrink-0 text-destructive" />
			<div class="min-w-0 flex-1 space-y-0.5">
				{#each saveError as row}
					<p class="text-xs text-destructive">
						{#if row.field}<span class="font-semibold">{row.field}: </span>{/if}{row.message}
					</p>
				{/each}
			</div>
			<button
				type="button"
				class="shrink-0 text-destructive/70 hover:text-destructive"
				onclick={() => onDismissSaveError?.()}
				aria-label="Cerrar error"
			>
				<X class="size-3.5" />
			</button>
		</div>
	{/if}

	{#if editingItem}
		<div class="max-h-[calc(90vh-96px)] overflow-auto bg-slate-50/60 p-6 dark:bg-black">
				<p class="mb-3 text-[10px] text-muted-foreground">
					{m.invoice_item_inv.required_fields_hint()}
				</p>
			<Tabs.Root bind:value={activeTab} class="mt-0">
				<Tabs.List class="grid w-full grid-cols-4">
					<Tabs.Trigger value="general">{m.invoice_item_inv.tab_general()}</Tabs.Trigger>
					<Tabs.Trigger value="clasificacion">{m.invoice_item_inv.tab_classification()}</Tabs.Trigger>
					<Tabs.Trigger value="cantidades">{m.invoice_item_inv.tab_quantities()}</Tabs.Trigger>
					<Tabs.Trigger value="otros">{m.invoice_item_inv.tab_other()}</Tabs.Trigger>
				</Tabs.List>

				<!-- Tab: General -->
				<Tabs.Content value="general" class="mt-4 space-y-4">
					<!-- Información de la Factura (Solo lectura) -->
					{#if !isTargetingPreset}
						<div class="space-y-3 rounded-lg border bg-muted/50 p-4">
							<h4 class="text-sm font-medium">{m.invoice_item_inv.invoice_info_title()} ({systemLabel})</h4>
							{#if !invoice?.id}
								<div class="rounded bg-amber-50 p-3 text-sm text-amber-600 dark:bg-amber-950/20">
									⚠️ {m.invoice_item_inv.invoice_unsaved_warning()}
								</div>
							{:else}
								<div class="grid grid-cols-2 gap-4 text-sm">
									<div>
										<span class="text-muted-foreground">{m.invoice_item_inv.invoice_id()}</span>
										<span class="ml-2 font-medium">{invoice.id}</span>
									</div>
									<div>
										<span class="text-muted-foreground">{m.invoice_item_inv.operation_type()}</span>
										<span class="ml-2 font-medium uppercase">{invoice.operation_type || 'N/A'}</span
										>
									</div>
									<div class="col-span-2">
											<span class="text-muted-foreground">{m.invoice_item_inv.invoice_number()}</span>
										<span class="ml-2 font-medium">{invoice.invoice_number || 'Pendiente'}</span>
									</div>
									<div class="col-span-2">
											<span class="text-muted-foreground">{m.invoice_item_inv.system()}</span>
										<span class="ml-2 rounded bg-blue-100 px-2 py-1 font-medium dark:bg-blue-900/30"
											>{systemLabel}</span
										>
									</div>
								</div>
							{/if}
						</div>
					{/if}

					<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
						<div class="space-y-2 md:col-span-2">
							<Label for="class_code">{m.invoice_item_inv.class_label()} <span class="text-red-500">*</span></Label>
							<div class="flex gap-1">
								<Input
									id="class_code"
									value={(editingItem as any).class_code || ''}
									readonly
									class="cursor-pointer bg-muted"
									placeholder={m.invoice_item_inv.select_class_placeholder()}
									onclick={() => (showClassDialog = true)}
									tabindex="0"
									onkeydown={(event) =>
										openOnEnterOrSpace(event, () => (showClassDialog = true))}
								/>
								<Button variant="outline" size="icon" onclick={() => (showClassDialog = true)}>
									<Folder class="h-4 w-4" />
								</Button>
							</div>
							{#if (editingItem as any).class_description}
								<p class="text-xs text-muted-foreground">{(editingItem as any).class_description}</p>
							{/if}
						</div>

						<div class="space-y-2">
							<Label for="quantity_general">{m.invoice_item_inv.quantity_label()} <span class="text-red-500">*</span></Label>
							{#if editingItem?.quantity}
								<Input id="quantity_general" type="number" step="0.00000001" min="0" bind:value={editingItem.quantity.quantity} />
							{/if}
						</div>
						<div class="space-y-2">
							<Label for="unit_general">{m.invoice_item_inv.unit_label()} <span class="text-red-500">*</span></Label>
							<div class="flex gap-1">
								<Input
									id="unit_general"
									value={(editingItem as any).unit_code || editingItem?.quantity?.unit_of_measure || ''}
									readonly
									class="cursor-pointer bg-muted"
									placeholder={m.invoice_item_inv.select_unit_placeholder()}
									onclick={() => (showUnitDialog = true)}
									tabindex="0"
									onkeydown={(event) =>
										openOnEnterOrSpace(event, () => (showUnitDialog = true))}
								/>
								<Button variant="outline" size="icon" onclick={() => (showUnitDialog = true)}>
									<Folder class="h-4 w-4" />
								</Button>
							</div>
						</div>

						<div class="space-y-2">
							<Label for="unit_cost_capture">{m.invoice_item_inv.unit_cost_label()} <span class="text-red-500">*</span></Label>
							{#if editingItem?.financial}
								<Input id="unit_cost_capture" type="number" step="0.00000001" min="0" bind:value={editingItem.financial.unit_cost_capture} />
							{/if}
						</div>
						<div class="space-y-2">
							<Label for="origin_country_general">{m.invoice_item_inv.country_label()} <span class="text-red-500">*</span></Label>
							<div class="flex gap-1">
								<Input
									id="origin_country_general"
									value={editingItem?.customs?.origin_country || ''}
									readonly
									class="cursor-pointer bg-muted"
									placeholder={m.invoice_item_inv.select_country_placeholder()}
									onclick={() => (showCountryDialog = true)}
									tabindex="0"
									onkeydown={(event) =>
										openOnEnterOrSpace(event, () => (showCountryDialog = true))}
								/>
								<Button variant="outline" size="icon" onclick={() => (showCountryDialog = true)}>
									<Folder class="h-4 w-4" />
								</Button>
							</div>
						</div>

						<div class="space-y-2">
							<Label for="fraction_general">{m.invoice_item_inv.fraction_label()} <span class="text-red-500">*</span></Label>
							<div class="flex gap-1">
								<Input
									id="fraction_general"
									value={fractionDisplay}
									readonly
									class="cursor-pointer bg-muted"
									placeholder={m.invoice_item_inv.select_fraction_placeholder()}
									onclick={() => (showFractionDialog = true)}
									tabindex="0"
									onkeydown={(event) =>
										openOnEnterOrSpace(event, () => (showFractionDialog = true))}
								/>
								<Button variant="outline" size="icon" onclick={() => (showFractionDialog = true)}>
									<Folder class="h-4 w-4" />
								</Button>
							</div>
						</div>
						<div class="space-y-2">
							<Label for="fraction_type_general">{m.invoice_item_inv.tariff_type_label()} <span class="text-red-500">*</span></Label>
							{#if editingItem?.customs}
								<select id="fraction_type_general" bind:value={editingItem.customs.fraction_type} class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
									<option value=""></option>
									<option value="GENERAL">GENERAL</option>
									<option value="PROSEC">PROSEC</option>
									<option value="ALADI">ALADI</option>
									<option value="TLCS">TLCS</option>
								</select>
							{/if}
						</div>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="reference_number">{m.invoice_item_inv.reference_number_label()}</Label>
							<Input id="reference_number" bind:value={editingItem.reference_number} />
						</div>
						<div class="space-y-2">
							<Label for="order">{m.invoice_item_inv.purchase_order_label()}</Label>
							<Input
								id="order"
								bind:value={editingItem.order}
								placeholder={invoice?.purchase_order || ''}
							/>
						</div>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="warehouse">{m.invoice_item_inv.warehouse_label()}</Label>
							<Input id="warehouse" bind:value={editingItem.warehouse} />
						</div>
						<div class="space-y-2">
							<Label for="location">{m.invoice_item_inv.location_label()}</Label>
							<Input id="location" bind:value={editingItem.location} />
						</div>
					</div>

					<!-- Campos específicos de SCAII: Descripciones -->
					<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="product_description_es">{m.invoice_item_inv.description_es_label()} <span class="text-red-500">*</span></Label>
							{#if editingItem?.description}
								<Input
									id="product_description_es"
									placeholder={m.invoice_item_inv.description_es_placeholder()}
									bind:value={editingItem.description.description_spanish}
								/>
							{/if}
						</div>
						<div class="space-y-2">
							<Label for="product_description_en">{m.invoice_item_inv.description_en_label()}</Label>
							{#if editingItem?.description}
								<Input
									id="product_description_en"
									placeholder={m.invoice_item_inv.description_en_placeholder()}
									bind:value={editingItem.description.description_english}
								/>
							{/if}
						</div>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="sku">{m.invoice_item_inv.sku_label()}</Label>
							{#if editingItem}
								<div class="flex gap-1">
									<Input
										id="sku"
										placeholder={m.invoice_item_inv.sku_placeholder()}
										value={(editingItem as any).part_number_display || ''}
										readonly
										class="cursor-pointer bg-muted"
										onclick={() => (showPartDialog = true)}
										tabindex="0"
										onkeydown={(event) =>
											openOnEnterOrSpace(event, () => (showPartDialog = true))}
									/>
									<Button variant="outline" size="icon" onclick={() => (showPartDialog = true)}>
										<Folder class="h-4 w-4" />
									</Button>
								</div>
							{/if}
						</div>
						<div class="space-y-2">
							<Label for="batch">{m.invoice_item_inv.batch_label()}</Label>
							{#if editingItem?.description}
								<Input id="batch" placeholder={m.invoice_item_inv.batch_placeholder()} bind:value={editingItem.description.lot} />
							{/if}
						</div>
					</div>
				</Tabs.Content>

				<!-- Tab: Clasificación -->
				<Tabs.Content value="clasificacion" class="mt-4 space-y-4">
					<div class="space-y-4">
						<div class="space-y-2">
								<Label for="tariff_fraction">{m.invoice_item_inv.classification_fraction_label()} <span class="text-red-500">*</span></Label>
							{#if editingItem?.customs}
								<div class="flex gap-1">
									<Input
										id="tariff_fraction"
										value={fractionDisplay}
										readonly
										class="cursor-pointer bg-muted"
										placeholder={m.invoice_item_inv.select_fraction_placeholder()}
										onclick={() => (showFractionDialog = true)}
										tabindex="0"
										onkeydown={(event) =>
											openOnEnterOrSpace(event, () => (showFractionDialog = true))}
									/>
									<Button variant="outline" size="icon" onclick={() => (showFractionDialog = true)}>
										<Folder class="h-4 w-4" />
									</Button>
								</div>
							{/if}
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="product_type">{m.invoice_item_inv.product_type_label()}</Label>
								{#if editingItem?.description}
									<Textarea
										id="product_type"
										placeholder={m.invoice_item_inv.product_type_placeholder()}
										bind:value={(editingItem.description as any).extra_description_2}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="material_type">{m.invoice_item_inv.material_type_label()}</Label>
								{#if editingItem?.description}
									<Textarea
										id="material_type"
										placeholder={m.invoice_item_inv.material_type_placeholder()}
										bind:value={(editingItem.description as any).extra_description_3}
									/>
								{/if}
							</div>
						</div>

						<div class="space-y-2">
							<Label for="product_code">{m.invoice_item_inv.product_code_label()}</Label>
							<Input id="product_code" placeholder={m.invoice_item_inv.product_code_placeholder()} />
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="country_origin">{m.invoice_item_inv.country_origin_label()} <span class="text-red-500">*</span></Label>
								{#if editingItem?.customs}
									<Input id="country_origin" placeholder={m.invoice_item_inv.country_code_placeholder()} bind:value={editingItem.customs.origin_country} />
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="merchandise_category">{m.invoice_item_inv.merchandise_category_label()}</Label>
								<Input id="merchandise_category" placeholder={m.invoice_item_inv.merchandise_category_placeholder()} />
							</div>
						</div>
					</div>
				</Tabs.Content>

				<!-- Tab: Cantidades -->
				<Tabs.Content value="cantidades" class="mt-4 space-y-4">
					<div class="space-y-4">
						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="quantity">{m.invoice_item_inv.quantity_tab_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="quantity"
										type="number"
										placeholder={m.invoice_item_inv.zero_placeholder()}
										bind:value={editingItem.quantity.quantity}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="unit">{m.invoice_item_inv.unit_of_measure_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="unit"
										placeholder={m.invoice_item_inv.unit_of_measure_placeholder()}
										bind:value={editingItem.quantity.unit_of_measure}
									/>
								{/if}
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="net_weight">{m.invoice_item_inv.net_weight_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="net_weight"
										type="number"
										step="0.01"
										placeholder={m.invoice_item_inv.decimal_placeholder()}
										bind:value={editingItem.quantity.net_weight}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="gross_weight">{m.invoice_item_inv.gross_weight_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="gross_weight"
										type="number"
										step="0.01"
										placeholder={m.invoice_item_inv.decimal_placeholder()}
										bind:value={editingItem.quantity.gross_weight}
									/>
								{/if}
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="unit_cost_usd">{m.invoice_item_inv.unit_cost_usd_label()}</Label>
								{#if editingItem?.financial}
									<Input
										id="unit_cost_usd"
										type="number"
										step="0.0001"
										placeholder={m.invoice_item_inv.decimal_placeholder()}
										bind:value={editingItem.financial.unit_cost_usd}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="total_value">{m.invoice_item_inv.total_value_label()}</Label>
								<Input
									id="total_value"
									type="number"
									step="0.01"
									placeholder={m.invoice_item_inv.decimal_placeholder()}
									value={(editingItem?.quantity?.quantity || 0) * (editingItem?.financial?.unit_cost_usd || 0)}
									disabled
								/>
							</div>
						</div>

						<!-- Campos específicos de SCAII -->
						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="packages">{m.invoice_item_inv.packages_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="packages"
										type="number"
										placeholder={m.invoice_item_inv.zero_placeholder()}
										bind:value={(editingItem.quantity as any).packages}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="package_type">{m.invoice_item_inv.package_type_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="package_type"
										placeholder={m.invoice_item_inv.package_type_placeholder()}
										bind:value={(editingItem.quantity as any).package_type}
									/>
								{/if}
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="imported_quantity">{m.invoice_item_inv.imported_quantity_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="imported_quantity"
										type="number"
										placeholder={m.invoice_item_inv.zero_placeholder()}
										bind:value={(editingItem.quantity as any).quantity_imported}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="remaining_quantity">{m.invoice_item_inv.remaining_quantity_label()}</Label>
								{#if editingItem?.quantity}
									<Input
										id="remaining_quantity"
										type="number"
										placeholder={m.invoice_item_inv.zero_placeholder()}
										value={(editingItem.quantity.quantity || 0) -
											((editingItem.quantity as any).quantity_imported || 0)}
										disabled
									/>
								{/if}
							</div>
						</div>
					</div>
				</Tabs.Content>

				<!-- Tab: Otros -->
				<Tabs.Content value="otros" class="mt-4 space-y-4">
					<div class="space-y-4">
						<div class="space-y-2">
							<Label for="brand">{m.invoice_item_inv.brand_label()}</Label>
							{#if editingItem?.description}
								<Input
									id="brand"
									placeholder={m.invoice_item_inv.brand_placeholder()}
									bind:value={editingItem.description.brand}
								/>
							{/if}
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="expiration_date">{m.invoice_item_inv.expiration_date_label()}</Label>
								<Input id="expiration_date" type="date" />
							</div>
							<div class="space-y-2">
								<Label for="production_date">{m.invoice_item_inv.production_date_label()}</Label>
								<Input id="production_date" type="date" />
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="min_stock">{m.invoice_item_inv.min_stock_label()}</Label>
								<Input id="min_stock" type="number" placeholder={m.invoice_item_inv.zero_placeholder()} />
							</div>
							<div class="space-y-2">
								<Label for="max_stock">{m.invoice_item_inv.max_stock_label()}</Label>
								<Input id="max_stock" type="number" placeholder={m.invoice_item_inv.zero_placeholder()} />
							</div>
						</div>

						<div class="space-y-2">
							<Label for="observations">{m.invoice_item_inv.observations_label()}</Label>
							{#if editingItem?.description}
								<textarea
									id="observations"
									class="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
									placeholder={m.invoice_item_inv.observations_placeholder()}
									bind:value={editingItem.description.extra_description}
								></textarea>
							{/if}
						</div>
					</div>
				</Tabs.Content>
			</Tabs.Root>
		</div>
		{:else}
			<div class="flex flex-col items-center justify-center py-20 text-muted-foreground">
				<Loader2 class="w-8 h-8 animate-spin mb-4" />
				<p class="text-sm">{m.invoice_item_inv.loading_item_data()}</p>
			</div>
		{/if}
	</Sheet.Content>
</Sheet.Root>
