<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';

	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);

	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;
		}
	}

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

<PartNumberDialog bind:open={showPartDialog} onSelect={handlePartSelect} />

<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'} - SCAII (Inventario)
				</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">
							{editingItem} items en esta partida
						</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 (SCAII - Inventario)</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"
											>SCAII (Inventory)</span
										>
									</div>
								</div>
							{/if}
						</div>
					{/if}

					<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>
								<Input id="country_origin" placeholder="Código del país" />
							</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>
