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

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

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

	// Format fraction with dots for display
	let fractionDisplay = $derived(() => {
		const frac = customs.fraction;
		if (!frac) return '';
		// If already has dots, return as is
		if (frac.includes('.')) return frac;
		// Format 8-digit fraction as XX.XX.XX.XX
		if (frac.length === 8) {
			return `${frac.slice(0, 4)}.${frac.slice(4, 6)}.${frac.slice(6, 8)}`;
		}
		// Format 10-digit fraction as XX.XX.XX.XXXX
		if (frac.length === 10) {
			return `${frac.slice(0, 4)}.${frac.slice(4, 6)}.${frac.slice(6, 8)}.${frac.slice(8, 10)}`;
		}
		return frac;
	});

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

	function normalizeFractionForBackend(raw: unknown) {
		if (raw === null || raw === undefined) return undefined;
		return String(raw).replace(/\./g, '').trim();
	}

	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 = normalizeFractionForBackend(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;
		
		// Only fetch if class_id changed, 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 || country.description_en;
	}

	function handleFractionSelect(fraction: any) {
		// Save without dots for backend, concatenating fraction + nico (8 + 2 = 10 chars)
		const fractionBase = fraction.fraction?.replace(/\./g, '') || '';
		const nico = fraction.nico || '';
		customs.fraction = fractionBase + nico;
		(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.substring(8, 10);
		const fractionType = customs.fraction_type;
		const invoiceDate = invoice?.invoice_date;

		// Only fetch if all required fields are present and fraction has at least 8 chars
		if (fraction && fraction.length >= 8 && nico && fractionType && invoiceDate) {
			const historicalFraction = fraction.substring(0, 8);
			const params = new URLSearchParams({
				historical_fraction: historicalFraction,
				nico: nico,
				fraction_type: fractionType,
				invoice_date: invoiceDate
			});

			fetch(`/api-sveltekit/historical-tariff-fractions/rate?${params}`)
				.then(response => {
					if (response.ok) {
						return response.json();
					}
					throw new Error('Failed to fetch tariff rate');
				})
				.then(data => {
					if (data.found && data.rate !== null) {
						customs.rate = data.rate;
					} else {
						customs.rate = '0';
					}
				})
				.catch(error => {
					console.error('Error fetching historical tariff rate:', error);
					// Keep current value on error
				});
		}
	});
</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">Main Data</legend>
	
	<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
					class="h-8 text-xs flex-1 bg-muted cursor-pointer" 
					placeholder="Selecciona una clase" 
					onclick={() => (showClassDialog = true)}
				/>
				<Button
					variant="outline"
					size="icon"
					class="h-8 w-8 shrink-0"
					onclick={() => (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">Quantity: <span class="text-red-500">*</span></Label>
			<Input id="cantidad" type="number" step="0.00000001" min="0" bind:value={quantities.quantity} class="h-8 text-xs text-right" />
		</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
					class="h-8 text-xs flex-1 bg-muted cursor-pointer" 
					placeholder="Selecciona U.M."
					onclick={() => (showUnitDialog = true)}
				/>
				<Button
					variant="outline"
					size="icon"
					class="h-8 w-8 shrink-0"
					onclick={() => (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">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} class="h-8 text-xs text-right flex-1" />
				<span class="text-xs text-zinc-900 dark:text-zinc-100 font-semibold">USD</span>
			</div>
		</div>

		<div class="space-y-1">
			<Label for="fraccion" class="text-xs font-medium">Fracción:</Label>
			<div class="flex gap-1">
				<Input 
					id="fraccion" 
					value={fractionDisplay()}
					readonly
					class="h-8 text-xs text-center flex-1 bg-muted cursor-pointer" 
					placeholder="Selecciona fracción"
					onclick={() => (showFractionDialog = true)}
				/>
				<Button
					variant="outline"
					size="icon"
					class="h-8 w-8 shrink-0"
					onclick={() => (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
					class="h-8 text-xs flex-1 bg-muted cursor-pointer" 
					placeholder="Selecciona país"
					onclick={() => (showCountryDialog = true)}
				/>
				<Button
					variant="outline"
					size="icon"
					class="h-8 w-8 shrink-0"
					onclick={() => (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">Tariff Type: <span class="text-red-500">*</span></Label>
				<select id="tipo_tarifa" bind:value={customs.fraction_type} 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">					
					<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>
