<script lang="ts">
	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 } 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';

	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;
	} = $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 handlePartSelect(part: any) {
		editingItem.part_number = part.id;
		// Store part number for display
		(editingItem as any).part_number_display = part.part_number;
		if (editingItem.description) {
			editingItem.description.description_spanish = part.description_spanish;
			editingItem.description.description_english = part.description_english;
		}
		if (editingItem.customs) {
			editingItem.customs.fraction = 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;
		editingItem.customs.origin_country = country.m3_key || country.mex_key;
		(editingItem.customs as any).origin_country_name = country.description || country.description_en;
	}

	function handleFractionSelect(fraction: any) {
		if (!editingItem.customs) editingItem.customs = {} as any;
		const fractionBase = fraction.fraction?.replace(/\./g, '') || '';
		const nico = fraction.nico || '';
		editingItem.customs.fraction = fractionBase + nico;
		(editingItem.customs as any).fraction_description = fraction.description;
	}

	const fractionDisplay = $derived.by(() => {
		const fraction = editingItem.customs?.fraction;
		if (!fraction) return '';
		if (fraction.includes('.')) return fraction;
		if (fraction.length === 8) return `${fraction.slice(0, 4)}.${fraction.slice(4, 6)}.${fraction.slice(6, 8)}`;
		if (fraction.length === 10) return `${fraction.slice(0, 4)}.${fraction.slice(4, 6)}.${fraction.slice(6, 8)}.${fraction.slice(8, 10)}`;
		return 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?.()
		})
	);

	// Derived state for easier binding and safety
	let line = $derived(editingItem);

	// Initialize missing nested objects if they don't exist
	$effect(() => {
		if (open && editingItem) {
			if (editingItem && !editingItem.quantity) editingItem.quantity = {} as any;
			if (editingItem && !editingItem.financial) editingItem.financial = {} as any;
			if (editingItem && !editingItem.customs) editingItem.customs = {} as any;
			if (editingItem && !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">
		<div
			class="flex items-start justify-between gap-3 border-b bg-white px-6 py-4 dark:bg-zinc-950"
		>
			<div class="space-y-1">
				<Sheet.Title class="text-lg font-semibold">
					{isEditMode ? 'Editar Item' : 'Agregar Nuevo Item'} - {systemLabel}
				</Sheet.Title>
				<Sheet.Description class="text-sm text-muted-foreground">
					{isEditMode
						? 'Modifica los campos del inventario y guarda los cambios.'
						: 'Completa la información del nuevo item de inventario.'}
					{#if editingItem}
						<Badge variant="secondary" class="ml-2">
							Línea {editingItem.line_number || 1}
						</Badge>
					{/if}
				</Sheet.Description>
			</div>
			<div class="flex gap-2">
				<Button variant="outline" onclick={() => onCancel?.()} disabled={isSaving}>Cancelar</Button>
				<Button onclick={onSave} disabled={isSaving}>
					{#if isSaving}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						Guardando...
					{:else}
						{isEditMode ? 'Guardar Cambios' : 'Agregar Item'}
					{/if}
				</Button>
			</div>
		</div>

		<div class="max-h-[calc(90vh-96px)] overflow-auto bg-slate-50/60 p-6 dark:bg-black">
			<Tabs.Root bind:value={activeTab} class="mt-0">
				<Tabs.List class="grid w-full grid-cols-4">
					<Tabs.Trigger value="general">General</Tabs.Trigger>
					<Tabs.Trigger value="clasificacion">Clasificación</Tabs.Trigger>
					<Tabs.Trigger value="cantidades">Cantidades</Tabs.Trigger>
					<Tabs.Trigger value="otros">Otros</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">Información de la Factura ({systemLabel})</h4>
							{#if !invoice?.id}
								<div class="rounded bg-amber-50 p-3 text-sm text-amber-600 dark:bg-amber-950/20">
									⚠️ Esta factura aún no se ha guardado. Los items se asociarán cuando guardes la
									factura.
								</div>
							{:else}
								<div class="grid grid-cols-2 gap-4 text-sm">
									<div>
										<span class="text-muted-foreground">ID Factura:</span>
										<span class="ml-2 font-medium">{invoice.id}</span>
									</div>
									<div>
										<span class="text-muted-foreground">Tipo Operación:</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">Número de Factura:</span>
										<span class="ml-2 font-medium">{invoice.invoice_number || 'Pendiente'}</span>
									</div>
									<div class="col-span-2">
										<span class="text-muted-foreground">Sistema:</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">Clase</Label>
							<div class="flex gap-1">
								<Input
									id="class_code"
									value={(editingItem as any).class_code || ''}
									readonly
									class="cursor-pointer bg-muted"
									placeholder="Selecciona una clase"
									onclick={() => (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">Cantidad</Label>
							{#if line?.quantity}
								<Input id="quantity_general" type="number" step="0.00000001" min="0" bind:value={line.quantity.quantity} />
							{/if}
						</div>
						<div class="space-y-2">
							<Label for="unit_general">U.M.</Label>
							<div class="flex gap-1">
								<Input
									id="unit_general"
									value={(editingItem as any).unit_code || line?.quantity?.unit_of_measure || ''}
									readonly
									class="cursor-pointer bg-muted"
									placeholder="Selecciona U.M."
									onclick={() => (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">Costo Unitario</Label>
							{#if line?.financial}
								<Input id="unit_cost_capture" type="number" step="0.00000001" min="0" bind:value={line.financial.unit_cost_capture} />
							{/if}
						</div>
						<div class="space-y-2">
							<Label for="origin_country_general">País de Origen</Label>
							<div class="flex gap-1">
								<Input
									id="origin_country_general"
									value={line?.customs?.origin_country || ''}
									readonly
									class="cursor-pointer bg-muted"
									placeholder="Selecciona país"
									onclick={() => (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">Fracción</Label>
							<div class="flex gap-1">
								<Input
									id="fraction_general"
									value={fractionDisplay}
									readonly
									class="cursor-pointer bg-muted"
									placeholder="Selecciona fracción"
									onclick={() => (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">Tipo de Tarifa</Label>
							<select id="fraction_type_general" bind:value={line.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>
						</div>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="reference_number">Número de Referencia</Label>
							<Input id="reference_number" bind:value={editingItem.reference_number} />
						</div>
						<div class="space-y-2">
							<Label for="order">Orden de Compra/Venta</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">Almacén</Label>
							<Input id="warehouse" bind:value={editingItem.warehouse} />
						</div>
						<div class="space-y-2">
							<Label for="location">Ubicación</Label>
							<Input id="location" bind:value={editingItem.location} />
						</div>
					</div>

					<!-- Campos específicos de SCAII -->
					<div class="space-y-2">
						<Label for="product_description">Descripción del Producto</Label>
						{#if line?.description}
							<Input
								id="product_description"
								placeholder="Descripción detallada del producto"
								bind:value={line.description.description_spanish}
							/>
						{/if}
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-2">
							<Label for="sku">SKU</Label>
							{#if line}
								<div class="flex gap-1">
									<Input
										id="sku"
										placeholder="Código SKU del producto"
										value={(line as any).part_number_display || ''}
										readonly
										class="cursor-pointer bg-muted"
										onclick={() => (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">Lote</Label>
							{#if line?.description}
								<Input id="batch" placeholder="Número de lote" bind:value={line.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">Fracción Arancelaria</Label>
							{#if line?.customs}
								<Input
									id="tariff_fraction"
									placeholder="8 dígitos"
									bind:value={line.customs.fraction}
								/>
							{/if}
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="product_type">Tipo de Producto</Label>
								{#if line?.description}
									<Textarea
										id="product_type"
										placeholder="Materia prima, producto terminado, etc."
										bind:value={(line.description as any).extra_description_2}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="material_type">Tipo de Material</Label>
								{#if line?.description}
									<Textarea
										id="material_type"
										placeholder="Metal, plástico, etc."
										bind:value={(line.description as any).extra_description_3}
									/>
								{/if}
							</div>
						</div>

						<div class="space-y-2">
							<Label for="product_code">Código de Producto</Label>
							<Input id="product_code" placeholder="Código interno" />
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="country_origin">País de Origen</Label>
								{#if line?.customs}
									<Input id="country_origin" placeholder="Código del país" bind:value={line.customs.origin_country} />
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="merchandise_category">Categoría de Mercancía</Label>
								<Input id="merchandise_category" placeholder="Categoría" />
							</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">Cantidad</Label>
								{#if line?.quantity}
									<Input
										id="quantity"
										type="number"
										placeholder="0"
										bind:value={line.quantity.quantity}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="unit">Unidad de Medida</Label>
								{#if line?.quantity}
									<Input
										id="unit"
										placeholder="PZA, KG, M, etc."
										bind:value={line.quantity.unit_of_measure}
									/>
								{/if}
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="net_weight">Peso Neto (KG)</Label>
								{#if line?.quantity}
									<Input
										id="net_weight"
										type="number"
										step="0.01"
										placeholder="0.00"
										bind:value={line.quantity.net_weight}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="gross_weight">Peso Bruto (KG)</Label>
								{#if line?.quantity}
									<Input
										id="gross_weight"
										type="number"
										step="0.01"
										placeholder="0.00"
										bind:value={line.quantity.gross_weight}
									/>
								{/if}
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="unit_cost_usd">Costo Unitario (USD)</Label>
								{#if line?.financial}
									<Input
										id="unit_cost_usd"
										type="number"
										step="0.0001"
										placeholder="0.00"
										bind:value={line.financial.unit_cost_usd}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="total_value">Valor Total (USD)</Label>
								<Input
									id="total_value"
									type="number"
									step="0.01"
									placeholder="0.00"
									value={(line?.quantity?.quantity || 0) * (line?.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">Número de Bultos</Label>
								{#if line?.quantity}
									<Input
										id="packages"
										type="number"
										placeholder="0"
										bind:value={(line.quantity as any).packages}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="package_type">Tipo de Empaque</Label>
								{#if line?.quantity}
									<Input
										id="package_type"
										placeholder="Caja, pallet, etc."
										bind:value={(line.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">Cantidad Importada</Label>
								{#if line?.quantity}
									<Input
										id="imported_quantity"
										type="number"
										placeholder="0"
										bind:value={(line.quantity as any).quantity_imported}
									/>
								{/if}
							</div>
							<div class="space-y-2">
								<Label for="remaining_quantity">Cantidad Remanente</Label>
								{#if line?.quantity}
									<Input
										id="remaining_quantity"
										type="number"
										placeholder="0"
										value={(line.quantity.quantity || 0) -
											((line.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">Marca</Label>
							{#if line?.description}
								<Input
									id="brand"
									placeholder="Marca del producto"
									bind:value={line.description.brand}
								/>
							{/if}
						</div>

						<div class="grid grid-cols-2 gap-4">
							<div class="space-y-2">
								<Label for="expiration_date">Fecha de Caducidad</Label>
								<Input id="expiration_date" type="date" />
							</div>
							<div class="space-y-2">
								<Label for="production_date">Fecha de Producción</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">Stock Mínimo</Label>
								<Input id="min_stock" type="number" placeholder="0" />
							</div>
							<div class="space-y-2">
								<Label for="max_stock">Stock Máximo</Label>
								<Input id="max_stock" type="number" placeholder="0" />
							</div>
						</div>

						<div class="space-y-2">
							<Label for="observations">Observaciones</Label>
							{#if line?.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="Notas adicionales sobre el inventario..."
									bind:value={line.description.extra_description}
								></textarea>
							{/if}
						</div>
					</div>
				</Tabs.Content>
			</Tabs.Root>
		</div>
	</Sheet.Content>
</Sheet.Root>
