<script lang="ts">
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Button } from '$lib/components/ui/button';
	import { Folder } from 'lucide-svelte';
    import type { Item, LineDescriptions, LineCustoms, LineQuantities } from '$lib/api/dashboard/a76/items';

	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import PackageDialog from './package-dialog.svelte';
	import USFractionSelectorDialog from '$lib/components/dashboard/goods/modales/us-fraction-selector-dialog.svelte';
	import type { TariffFraction } from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
	import { m } from '$lib/i18n/messages';

    let {
        item = $bindable(),
        lineItem = $bindable(),
        descriptions = $bindable(),
        customs = $bindable(),
		quantities = $bindable(),
		invoice,
		disabled = false
    }: {
        item: Partial<Item>;
        lineItem: any;
        descriptions: LineDescriptions;
        customs: LineCustoms;
		quantities: LineQuantities;
		invoice: Invoice | null;
		disabled?: boolean;
    } = $props();



	let packageDialogOpen = $state(false);
	let americanFractionDialogOpen = $state(false);
	let package_key = $state('');
	let package_weight_unit = $state<number>(0);
	let isLoadingPackage = $state(false);

	// Get weight unit from invoice logistics or default to 'KILOS'
	const weightUnitLabel = $derived.by(() => {
		const weightType = invoice?.logistics?.weight_type?.toUpperCase();
		if (weightType === 'KGS') return 'KILOS';
		if (weightType === 'LBS') return 'LIBRAS';
		return 'KILOS'; // Default
	});

	// Calculate total package weight
	const totalPackageWeightNum = $derived.by(() => {
		const qty = Number(quantities.package_quantity ?? 0);
		const weightPerUnit = Number(package_weight_unit ?? 0);
		return qty * weightPerUnit;
	});

	const totalPackageWeight = $derived.by(() => totalPackageWeightNum.toFixed(4));
	const computedGrossWeight = $derived.by(() => {
		const net = Number(quantities.net_weight ?? 0);
		return net + totalPackageWeightNum;
	});

	// Auto-calculate gross weight = net weight + weight of packages (if gross wasn't provided)
	$effect(() => {
		const netWeight = quantities.net_weight;
		if (netWeight === null || netWeight === undefined) return;

		const currentGross = quantities.gross_weight;
		const shouldAutoFill = currentGross === null || currentGross === undefined || Number(currentGross) === 0;
		if (!shouldAutoFill) return;

		// Keep precision stable enough for the UI inputs.
		quantities.gross_weight = Number(computedGrossWeight.toFixed(8));
	});

	// Load or sync package data when package_id exists
	$effect(() => {
		async function loadPackageData() {
			// Si ya tiene package_key en quantities (cargado por enrichItemData), usarlo
			if ((quantities as any).package_key) {
				package_key = (quantities as any).package_key;
				package_weight_unit = (quantities as any).package_weight_unit || 0;
				return;
			}

			// Si no, pero tiene package_id, cargar los datos
			if (quantities.package_id && !package_key && !isLoadingPackage) {
				isLoadingPackage = true;
				try {
					const response = await fetch('/api-sveltekit/packages', {
						credentials: 'include'
					});
					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 === quantities.package_id);
							if (pkg) {
								package_key = pkg.key;
								package_weight_unit = pkg.weight_unit || 0;
								if (!quantities.package_description) {
									quantities.package_description = pkg.description_es || pkg.description_en || pkg.key;
								}
							}
						}
					}
				} catch (error) {
					console.error('Error loading package data:', error);
				} finally {
					isLoadingPackage = false;
				}
			}
		}
		loadPackageData();
	});

	function handlePackageSelect(pkg: any) {
		quantities.package_id = pkg.id;
		package_key = pkg.key;
		package_weight_unit = pkg.weight_unit || 0;
		quantities.package_description = pkg.description_es || pkg.description_en || pkg.key;
	}

	function handleAmericanFractionSelect(fraction: TariffFraction) {
		customs.american_fraction = fraction.code || '';
		(customs as any).american_fraction_description = fraction.description || '';
		if (fraction.adv_impo != null && String(fraction.adv_impo).trim() !== '') {
			const n = parseFloat(String(fraction.adv_impo).replace('%', '').trim());
			if (!Number.isNaN(n)) customs.advalorem_american = n;
		}
	}

	const isPackageRequired = $derived(!!quantities.package_id || (Number(quantities.package_quantity) > 0));
</script>

<fieldset class="border rounded-md p-2 space-y-2">
	<legend class="text-xs font-semibold px-2 bg-gray-200 dark:bg-gray-700">{m['invoice_item_fa.packages.legend']()}</legend>
	<p class="text-[10px] text-muted-foreground px-1">
		Los campos marcados con * son obligatorios.
	</p>
	
	<div class="grid grid-cols-12 gap-2 items-end">
		<div class="col-span-2 space-y-1">
			<Label for="cantidad_bultos" class="text-xs">
				{m['invoice_item_fa.packages.quantity']()}: 
				{#if isPackageRequired}<span class="text-red-500">*</span>{/if}
			</Label>
			<Input id="cantidad_bultos" type="number" step="1" min="0" bind:value={quantities.package_quantity} disabled={disabled} class="h-7 text-xs text-right" />
		</div>

		<div class="col-span-3 space-y-1">
			<Label for="clave_bultos" class="text-xs">
				{m['invoice_item_fa.packages.package_code']()}: 
				{#if isPackageRequired}<span class="text-red-500">*</span>{/if}
			</Label>
			<div class="flex gap-1">
				<Input 
					id="clave_bultos" 
					bind:value={package_key} 
					class="h-7 text-xs flex-1"
					readonly
					disabled={disabled}
					placeholder="Seleccionar..."
					onclick={() => !disabled && (packageDialogOpen = true)}
				/>

				<Button 
					size="icon" 
					variant="outline" 
					class="h-7 w-7 shrink-0"
					disabled={disabled}
					onclick={() => !disabled && (packageDialogOpen = true)}
					type="button"
				>
					<Folder class="h-3 w-3" />
				</Button>

			</div>
		</div>
		<div class="col-span-1 flex items-end">								
		</div>
	</div>

	<div class="grid grid-cols-12 gap-2 items-end">
		<div class="col-span-2 space-y-1">
			<Label for="peso_bultos" class="text-xs">{m['invoice_item_fa.packages.weight']()}: {totalPackageWeight}</Label>
		</div>
		<div class="col-span-4 space-y-1">
			<Label for="descripcion_bultos" class="text-xs">{m['invoice_item_fa.packages.description']()}: {quantities.package_description || ''}</Label>
		</div>
	</div>

	<!-- WEIGHTS subsection -->
	<div class="border-t pt-2">
		<div class="text-xs font-semibold mb-2">{m['invoice_item_fa.packages.weights']()}</div>
		<div class="grid grid-cols-6 gap-2 items-end">
			<div class="col-span-2 space-y-1">
				<Label for="peso_neto" class="text-xs">{m['invoice_item_fa.packages.net']()}: <span class="text-red-500">*</span></Label>
				<Input id="peso_neto" type="number" step="0.00000001" min="0" bind:value={quantities.net_weight} disabled={disabled} class="h-7 text-xs text-right" data-item-validation-path="quantity.net_weight" />
			</div>

			<div class="col-span-2 space-y-1">
				<Label for="peso_bruto" class="text-xs">{m['invoice_item_fa.packages.gross']()}:</Label>
				<Input id="peso_bruto" type="number" step="0.00000001" min="0" bind:value={quantities.gross_weight} disabled={disabled} class="h-7 text-xs text-right" data-item-validation-path="quantity.gross_weight" />
			</div>

			<div class="col-span-2 space-y-1">
				<Label class="text-xs invisible">{m['invoice_item_fa.packages.space']()}</Label>
				<span class="text-xs text-gray-900 dark:text-gray-100 font-semibold">{weightUnitLabel}</span>
			</div>
		</div>
	</div>

	<div class="grid grid-cols-12 gap-2 items-end">
		<div class="col-span-2 space-y-1">
			<Label for="no_permiso" class="text-xs">{m['invoice_item_fa.packages.permit_number']()}:</Label>
			<Input id="no_permiso" bind:value={lineItem.permit_number} disabled={disabled} class="h-7 text-xs" />
		</div>

		<div class="col-span-3 space-y-1">
			<Label for="pag_region" class="text-xs">{m['invoice_item_fa.packages.page_region']()}:</Label>
			<Input id="pag_region" bind:value={lineItem.page_line} disabled={disabled} class="h-7 text-xs" />
		</div>

	</div>

	<div class="grid grid-cols-12 gap-2 items-end">
		<div class="col-span-4 space-y-1">
			<Label for="fraccion_americana" class="text-xs">{m['invoice_item_fa.packages.american_fraction']()}: <span class="text-red-500">*</span></Label>
			<div class="flex gap-1">
			<Input
				id="fraccion_americana"
				value={customs.american_fraction || ''}
				readonly
				disabled={disabled}
				class="h-7 text-xs flex-1 bg-muted cursor-pointer"
				placeholder="Seleccionar..."
				onclick={() => !disabled && (americanFractionDialogOpen = true)}
				data-item-validation-path="customs.american_fraction"
			/>
				<Button
					type="button"
					variant="outline"
					size="icon"
					class="h-7 w-7 shrink-0"
					disabled={disabled}
					onclick={() => !disabled && (americanFractionDialogOpen = true)}
				>
					<Folder class="h-3 w-3" />
				</Button>
			</div>
		</div>							

		<div class="col-span-3 space-y-1">
			<Label class="text-xs invisible">{m['invoice_item_fa.packages.space']()}</Label>
			<span class="text-xs">Advalorem: {customs.advalorem_american || '0.00'}</span>
		</div>
	</div>

	<div class="grid grid-cols-9 gap-2 items-end">
		<div class="col-span-3 space-y-1">
			<Label for="marca" class="text-xs">{m['invoice_item_fa.packages.brand']()}:</Label>
			<Input id="marca" bind:value={descriptions.brand} disabled={disabled} class="h-7 text-xs" />
		</div>

		<div class="col-span-3 space-y-1">
			<Label for="modelo" class="text-xs">{m['invoice_item_fa.packages.model']()}:</Label>
			<Input id="modelo" bind:value={descriptions.model} disabled={disabled} class="h-7 text-xs" />
		</div>

		<div class="col-span-3 space-y-1">
			<Label for="orden_compra" class="text-xs">{m['invoice_item_fa.packages.purchase_order']()}:</Label>
			<Input id="orden_compra" bind:value={item.order} disabled={disabled} class="h-7 text-xs" />
		</div>						

	</div>							
</fieldset>

<PackageDialog bind:open={packageDialogOpen} onSelect={handlePackageSelect} />
<USFractionSelectorDialog bind:open={americanFractionDialogOpen} onSelect={handleAmericanFractionSelect} />
