<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 UnitOfMeasureDialog from './unit-of-measure-dialog.svelte';
	import CountryDialog from './country-dialog.svelte';
	import TariffFractionDialog from './tariff-fraction-dialog.svelte';
	import ClassDialog from './class-dialog.svelte';
	import type { Item, LineQuantities, LineFinancials, LineCustoms } from '$lib/api/dashboard/a76/items';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		buildMexTariffDigitsFromCatalogRow,
		formatMexTariffDigitsForDisplay,
		normalizeMexTariffDigitsStored
	} from '$lib/utils/mexican-tariff-fraction';
	import { m } from '$lib/i18n/messages';

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

    
    const activeCompanyId = $derived(companyStore?.activeCompany?.id);

	let showClassDialog = $state(false);
	let showUnitDialog = $state(false);
	let showCountryDialog = $state(false);
	let showFractionDialog = $state(false);

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

	let isDischargeActive = $derived(lineItem.fa_data?.discharge === true);

	// Track previous class_id to detect changes
	let previousClassId = $state<number | undefined>(undefined);

	async function getUnitByCode(unitCode: string) {
		const activeCompanyId = companyStore?.activeCompany?.id;
		if (!unitCode || !activeCompanyId) return undefined;

		try {
			const res = await fetch(
				`/api-sveltekit/units-of-measure?code=${encodeURIComponent(unitCode)}&page=1&page_size=20`,
				{
					method: 'GET',
					credentials: 'include'
				}
			);
			if (!res.ok) return undefined;
			const data = await res.json();
			const units = data?.items || data?.data || data;
			if (Array.isArray(units) && units.length > 0) return units[0];
		} catch {
			// Ignore unit lookup failures and let the user fix manually.
		}

		return undefined;
	}

	async function applyClassDefaults(classItem: any) {
		if (!classItem) return;

		// Class display fields
		(lineItem as any).class_code = classItem.class_code;
		(lineItem as any).class_unit_of_measure = classItem.unit_of_measure;
		(lineItem as any).class_description = classItem.description_es || classItem.description_en;

		// Descriptions
		if ((lineItem as any).description) {
			const desc = (lineItem as any).description;
			// Use != null (instead of truthy) to support valid empty strings
			if (classItem.description_es != null) desc.description_spanish = classItem.description_es;
			if (classItem.description_en != null) desc.description_english = classItem.description_en;
		}

		// U.M. (display + internal FK id)
		const classUnitCode = classItem.unit_of_measure;
		if (classUnitCode != null) {
			// Always set display code if missing.
			if (!(lineItem as any).unit_code) (lineItem as any).unit_code = classUnitCode;

			// Only resolve and override the FK if it isn't set yet.
			if (!lineItem.unit_of_measure) {
				const unit = await getUnitByCode(String(classUnitCode));
				if (unit) {
					lineItem.unit_of_measure = unit.id;
					(lineItem as any).unit_code = unit.code;
					(lineItem as any).unit_description = unit.description || unit.description_en;
					quantities.unit_of_measure = unit.code;
				}
			}
		}

		// Fracción arancelaria (Mex / SCAII)
		if (!customs.fraction && classItem.fraction != null) {
			customs.fraction = normalizeMexTariffDigitsStored(
				String(classItem.import_tariff_code || classItem.fraction || '')
			);
		}

		// Tipo de fracción
		if (!customs.fraction_type && classItem.import_tariff_type) {
			customs.fraction_type = classItem.import_tariff_type;
		}

		// Fracción americana (HTS / US)
		if (!customs.american_fraction && classItem.us_fraction) {
			customs.american_fraction = classItem.us_fraction;
		}
	}

	// Watch for class_id changes and update descriptions automatically
	$effect(() => {
		const currentClassId = lineItem.class_id;
		const activeCompanyId = companyStore?.activeCompany?.id;

		// Initial load protection: If previousClassId is undefined, this is the first run.
		// We set previousClassId to the current value without fetching catalog defaults
		// if we are opening an existing record that already has a class.
		if (previousClassId === undefined && currentClassId) {
			previousClassId = currentClassId;
			return;
		}
		
		// Only fetch and apply defaults if class_id changed from a previous value, 
		// is valid, and we have a company.
		if (currentClassId && currentClassId !== previousClassId && activeCompanyId) {
			previousClassId = currentClassId;
			
			// Fetch all classes and find the one with matching ID
			fetch(`/api-sveltekit/classes?company_id=${activeCompanyId}&limit=100`)
				.then(response => {
					if (response.ok) {
						return response.json();
					}
					throw new Error('Failed to fetch classes');
				})
				.then(data => {
					const classes = data.items || [];
					const classItem = classes.find((c: any) => c.id === currentClassId);
					
					if (classItem) {
						// Apply defaults derived from catalog class selection.
						void applyClassDefaults(classItem);
					}
				})
				.catch(error => {
					console.error('Error fetching class data:', error);
				});
		}
	});

	function handleClassSelect(classItem: any) {
		lineItem.class_id = classItem.id;
		void applyClassDefaults(classItem);
	};

	function handleUnitSelect(unit: any) {
		lineItem.unit_of_measure = unit.id;				
		// Store unit code for display
		(lineItem as any).unit_code = unit.code;
		(lineItem as any).unit_description = unit.description || unit.description_en;
	}

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

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

	// Auto-fetch historical tariff rate when fraction, country, type, and date are available
	$effect(() => {
		const fraction = customs.fraction?.replace(/\./g, '') || '';
		const nico = fraction.length >= 10 ? fraction.substring(8, 10) : '00';
		const tariffType = customs.fraction_type || 'GENERAL';
		const invoiceDate = invoice?.invoice_date;
		
		// Map invoice movement type to direction string
		const direction = invoice?.operation_type === 'imp' ? 'import' : 'export';

		// Only fetch if all required fields are present and fraction has at least 8 chars
		if (activeCompanyId && fraction && fraction.length >= 8 && tariffType && invoiceDate) {
			const historicalFraction = fraction.substring(0, 8);
			const isRegimeChange = invoice?.compliance_mx?.is_regime_change ? 'true' : 'false';
			
			// Format date to YYYY-MM-DD
			let formattedDate = '';
			if (invoiceDate) {
				const dateObj = typeof invoiceDate === 'string' ? new Date(invoiceDate) : invoiceDate;
				formattedDate = dateObj.toISOString().split('T')[0];
			}

			if (!formattedDate) return;

			const params = new URLSearchParams({
				company_id: activeCompanyId.toString(),
				historical_fraction: historicalFraction,
				nico: nico,
				direction: direction,
				tariff_type: tariffType,
				invoice_date: formattedDate,
				is_regime_change: isRegimeChange
			});

			fetch(`/api-sveltekit/historical-tariff-fractions/rate?${params}`)
				.then(async response => {
					if (response.ok) {
						return response.json();
					}
					// If 422 or other error, try to extract the specific detail from FastAPI
					let errorMsg = `HTTP ${response.status}`;
					try {
						const errData = await response.json();
						if (errData.detail) {
							errorMsg = typeof errData.detail === 'string' ? errData.detail : JSON.stringify(errData.detail);
						} else if (errData.details || errData.error) {
							errorMsg = errData.details || errData.error;
						}
					} catch (e) {
						errorMsg = await response.text().catch(() => `Error ${response.status}`);
					}
					
					console.warn('Historical tariff lookup failed at backend:', errorMsg);
					return { found: false, rate: 0 };
				})
				.then(data => {
					if (data && data.found && data.rate !== null) {
						customs.rate = String(data.rate).substring(0, 10);
					} else {
						customs.rate = '0';
					}
				})
				.catch(error => {
					console.warn('Historical tariff lookup network error:', error);
				});
		}
	});

	/**
	 * Centralized calculation logic based on the Clarion routine
	 * @param source - Which field triggered the update
	 */
	function recalculateFinancials(source: 'total' | 'unit_cost' | 'quantity') {
		const qty = Number(quantities.quantity || 0);
		const exchangeRate = Number(invoice?.financials?.exchange_rate || 1);
		const exchangeRateMM = Number(invoice?.financials?.exchange_rate_mm || 1);
		const ivaFactor = Number(invoice?.financials?.iva_factor || 0);
		const currencyType = invoice?.financials?.currency_type || 'USD';

		// 1. Synchronize Unit Cost and Total
		if (source === 'total') {
			if (qty > 0) {
				financials.unit_cost_capture = Number(financials.value_mc || 0) / qty;
			}
		} else {
			// source is unit_cost or quantity
			financials.value_mc = Number(financials.unit_cost_capture || 0) * qty;
		}

		const unitCostCapture = Number(financials.unit_cost_capture || 0);
		const valueCapture = Number(financials.value_mc || 0);

		// 2. Perform Triangulation based on Currency Type
		if (currencyType === 'ME' || currencyType === 'FOREIGN' || currencyType === 'USD') {
			financials.unit_cost_usd = unitCostCapture;
			financials.unit_cost_mxn = unitCostCapture * exchangeRate;
			financials.value_usd = valueCapture;
			financials.value_mxn = valueCapture * exchangeRate;
		} else if (currencyType === 'MN' || currencyType === 'LOCAL' || currencyType === 'MXN') {
			financials.unit_cost_mxn = unitCostCapture;
			financials.unit_cost_usd = exchangeRate > 0 ? unitCostCapture / exchangeRate : 0;
			financials.value_mxn = valueCapture;
			financials.value_usd = exchangeRate > 0 ? valueCapture / exchangeRate : 0;
		} else if (currencyType === 'MC') {
			financials.unit_cost_mc = unitCostCapture;
			// Clarion logic for MC: 
			// 1. Convert Capture to USD using exchangeRateMM (TipoCambioMM)
			financials.unit_cost_usd = unitCostCapture * exchangeRateMM;
			// 2. Convert resulting USD to MXN using exchangeRate (TipoCambio)
			financials.unit_cost_mxn = financials.unit_cost_usd * exchangeRate;
			
			financials.value_mc = valueCapture;
			financials.value_usd = financials.unit_cost_usd * qty;
			financials.value_mxn = financials.unit_cost_mxn * qty;
		}

		// 3. VAT Calculation
		financials.vat_mxn = (Number(financials.value_mxn || 0) * ivaFactor) / 100;
		financials.vat_usd = (Number(financials.value_usd || 0) * ivaFactor) / 100;
		financials.vat_mc = (Number(financials.value_mc || 0) * ivaFactor) / 100;
	}
</script>

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

<fieldset class="border rounded-md p-3">
	<legend class="text-xs font-semibold px-2 bg-zinc-200 dark:bg-zinc-700">{m['invoice_item_fa.main_data.legend']()}</legend>
	<p class="mt-1 px-1 text-[10px] text-muted-foreground">
		Los campos marcados con * son obligatorios.
	</p>
	
	<div class="grid grid-cols-2 gap-4">
		<!-- Class - Full Width -->
		<div class="col-span-2 space-y-1">
			<Label for="clase" class="text-xs font-medium">Clase: <span class="text-red-500">*</span></Label>
			<div class="flex gap-1">
			<Input 
				id="clase" 
				type="text" 
				value={(lineItem as any).class_code || ''}
				readonly
				disabled={disabled || isDischargeActive}
				class="h-8 text-xs flex-1 bg-muted cursor-pointer" 
				placeholder="Selecciona una clase" 
				onclick={() => !disabled && !isDischargeActive && (showClassDialog = true)}
				data-item-validation-path="class_id"
			/>
				<Button
					variant="outline"
					size="icon"
					disabled={disabled || isDischargeActive}
					class="h-8 w-8 shrink-0"
					onclick={() => !disabled && !isDischargeActive && (showClassDialog = true)}
				>

					<Folder class="w-4 h-4" />
				</Button>
			</div>
			{#if (lineItem as any).class_description}
				<p class="text-xs text-muted-foreground">{(lineItem as any).class_description}</p>
			{/if}
		</div>

		<!-- Quantity and U.M. on the same row -->
		<div class="space-y-1">
			<Label for="cantidad" class="text-xs font-medium">{m['invoice_item_fa.main_data.quantity']()}: <span class="text-red-500">*</span></Label>
		<Input 
			id="cantidad" 
			type="number" 
			step="0.00000001" 
			min="0" 
			bind:value={quantities.quantity} 
			disabled={disabled}
			oninput={() => recalculateFinancials('quantity')}
			class="h-8 text-xs text-right"
			data-item-validation-path="quantity.quantity"
		/>

			{#if isDischargeActive && lineItem.fa_data?.source_balance !== undefined && Number(quantities.quantity) > Number(lineItem.fa_data.source_balance)}
				<p class="text-[10px] text-red-500 font-bold mt-1 animate-pulse bg-red-50 dark:bg-red-900/20 px-1.5 py-0.5 rounded border border-red-200 dark:border-red-800/50">
					⚠️ Excede saldo disponible ({lineItem.fa_data.source_balance})
				</p>
			{/if}
		</div>

		<div class="space-y-1">
			<Label class="text-xs font-medium">U.M.: <span class="text-red-500">*</span></Label>
			<div class="flex gap-1">
			<Input 
				id="um" 
				type="text" 
				value={(lineItem as any).unit_code || ''}
				readonly
				disabled={disabled || isDischargeActive}
				class="h-8 text-xs flex-1 bg-muted cursor-pointer" 
				placeholder="Selecciona U.M."
				onclick={() => !disabled && !isDischargeActive && (showUnitDialog = true)}
				data-item-validation-path="unit_of_measure"
			/>
				<Button
					variant="outline"
					size="icon"
					disabled={disabled || isDischargeActive}
					class="h-8 w-8 shrink-0"
					onclick={() => !disabled && !isDischargeActive && (showUnitDialog = true)}
				>
					<Folder class="w-4 h-4" />
				</Button>

			</div>
		</div>

		<!-- Unit Cost and Fraction -->
		<div class="space-y-1">
			<Label for="costo_unitario" class="text-xs font-medium">{m['invoice_item_fa.main_data.unit_cost']()}: <span class="text-red-500">*</span></Label>
			<div class="flex items-center gap-2">
			<Input 
				id="costo_unitario" 
				type="number" 
				step="0.00000001" 
				min="0" 
				bind:value={financials.unit_cost_capture} 
				disabled={disabled}
				oninput={() => recalculateFinancials('unit_cost')}
				class="h-8 text-xs text-right flex-1"
				data-item-validation-path="financial.unit_cost_capture"
			/>

				<span class="text-xs text-zinc-900 dark:text-zinc-100 font-semibold">{invoice?.financials?.currency_type || 'USD'}</span>
			</div>
		</div>

		<div class="space-y-1">
			<Label for="valor_total" class="text-xs font-medium">{m['invoice_item_fa.main_data.total_value']()}:</Label>
			<div class="flex items-center gap-2">
				<Input 
					id="valor_total" 
					type="number" 
					step="0.00000001" 
					min="0" 
					bind:value={financials.value_mc} 
					disabled={disabled}
					oninput={() => recalculateFinancials('total')}
					class="h-8 text-xs text-right flex-1" 
				/>

				<span class="text-xs text-zinc-900 dark:text-zinc-100 font-semibold">{invoice?.financials?.currency_type || 'USD'}</span>
			</div>
		</div>

		<div class="space-y-1">
			<Label for="fraccion" class="text-xs font-medium">Fracción: <span class="text-red-500">*</span></Label>
			<div class="flex gap-1">
			<Input 
				id="fraccion" 
				value={fractionDisplay}
				readonly
				disabled={disabled}
				class="h-8 text-xs text-center flex-1 bg-muted cursor-pointer" 
				placeholder="Selecciona fracción"
				onclick={() => !disabled && (showFractionDialog = true)}
				data-item-validation-path="customs.fraction"
			/>
				<Button
					variant="outline"
					size="icon"
					disabled={disabled}
					class="h-8 w-8 shrink-0"
					onclick={() => !disabled && (showFractionDialog = true)}
				>
					<Folder class="w-4 h-4" />
				</Button>

			</div>
		</div>

		<!-- Origin Country and Tariff Type -->
		<div class="space-y-1">
			<Label for="pais_origen" class="text-xs font-medium">País de Origen: <span class="text-red-500">*</span></Label>
			<div class="flex gap-1">
			<Input 
				id="pais_origen" 
				value={customs.origin_country || ''}
				readonly
				disabled={disabled}
				class="h-8 text-xs flex-1 bg-muted cursor-pointer" 
				placeholder="Selecciona país"
				onclick={() => !disabled && (showCountryDialog = true)}
				data-item-validation-path="customs.origin_country"
			/>
				<Button
					variant="outline"
					size="icon"
					disabled={disabled}
					class="h-8 w-8 shrink-0"
					onclick={() => !disabled && (showCountryDialog = true)}
				>
					<Folder class="w-4 h-4" />
				</Button>

			</div>		
		</div>

		<div class="flex items-end gap-6">
			<div class="space-y-1">
				<Label for="tipo_tarifa" class="text-xs font-medium">{m['invoice_item_fa.main_data.tariff_type']()}: <span class="text-red-500">*</span></Label>
				<select id="tipo_tarifa" bind:value={customs.fraction_type} disabled={disabled} class="flex h-8 w-auto min-w-[140px] rounded-md border border-input bg-background px-2 py-1 text-xs ring-offset-background" data-item-validation-path="customs.fraction_type">					
					<option value="GENERAL">GENERAL</option>
					<option value="PROSEC">PROSEC</option>
					<option value="ALADI">ALADI</option>
					<option value="TLCS">TLCS</option>
				</select>

			</div>

			<!-- Advalorem -->
			<div class="flex items-center gap-2 h-8 pb-0.5">
				<span class="text-xs font-medium text-muted-foreground">Advalorem:</span>
				<span class="text-xs text-zinc-900 dark:text-zinc-100 font-semibold">
					{customs.rate || '0'}
				</span>
			</div>
		</div>
	</div>
</fieldset>
