<script lang="ts">
    import type { LineFinancials, LineQuantities, Item } from '$lib/api/dashboard/a76/items';
    import type { Invoice } from '$lib/api/dashboard/a76/invoices';
    import type { Part } from '$lib/api/dashboard/a76/parts';
    import { companyStore } from '$lib/stores/company.svelte';
    import { m } from '$lib/i18n/messages';

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


	// Helper function to safely format numbers
	function formatNumber(value: any, decimals: number = 8): string {
		const num = Number(value);
		return isNaN(num) ? '0.00000000' : num.toFixed(decimals);
	}

    // ========== ESTRUCTURA DE COMPARACIÓN DE MONEDAS ==========  
    
    // Extraer las monedas del invoice y del part
    let invoiceCurrency = $derived(invoice?.financials?.currency_type);    

    // Effect para actualizar los costos unitarios en diferentes monedas cuando cambie unit_cost_capture
    $effect(() => {
        const exchangeRate = invoice?.financials?.exchange_rate || 1;
        const unitCostCapture = financials.unit_cost_capture || 1;
        
        // Calcular unit_cost_usd y unit_cost_mxn basado en la moneda del invoice
        if (invoiceCurrency === 'USD') {
            financials.unit_cost_usd = unitCostCapture;
            financials.unit_cost_mxn = unitCostCapture * exchangeRate;
        } else if (invoiceCurrency === 'MXN') {
            financials.unit_cost_mxn = unitCostCapture;
            financials.unit_cost_usd = unitCostCapture / exchangeRate;
        } else {
            // Por defecto, si no hay moneda definida, asumir USD
            financials.unit_cost_usd = unitCostCapture;
            financials.unit_cost_mxn = unitCostCapture * exchangeRate;
        }
    });

    let calculatedValueCapture = $derived.by(() => {
        const quantity = quantities.quantity || 0;
        const unitCost = financials.unit_cost_capture;
        
        // Calcular el valor total (costo unitario * cantidad)
        return (unitCost || 0)  * quantity;
    });  

    // Effect para actualizar los valores en diferentes monedas cuando cambie calculatedValueCapture
    $effect(() => {
        const exchangeRate = invoice?.financials?.exchange_rate || 1;		
        const valueCapture = calculatedValueCapture;
        
        // value_mc es el valor en la moneda de captura (invoice currency)
        financials.value_mc = valueCapture;
        
        // Calcular value_usd y value_mxn basado en la moneda del invoice
        if (invoiceCurrency === 'USD') {
            financials.value_usd = valueCapture;
            financials.value_mxn = valueCapture * exchangeRate;
        } else if (invoiceCurrency === 'MXN') {
            financials.value_mxn = valueCapture;
            financials.value_usd = valueCapture / exchangeRate;
        } else {
            // Por defecto, si no hay moneda definida, asumir USD
            financials.value_usd = valueCapture;
            financials.value_mxn = valueCapture * exchangeRate;
        }
    });

    // ========== FIN ESTRUCTURA DE COMPARACIÓN ==========
</script>

<div>
	<fieldset class="border rounded-md p-2 space-y-1 bg-red-50 dark:bg-red-950/20">
        <legend class="text-xs font-semibold px-2 bg-red-700 text-white">{m['invoice_item_fa.summary.general_data']()}</legend>
		
        <div class="text-xs font-semibold">{m['invoice_item_fa.summary.return_quantity_subitems']()}</div>
		<div class="grid grid-cols-2 gap-2 text-xs">
            <div>{m['invoice_item_fa.summary.temporary']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(quantities.quantity_temp_export)}</span></div>
            <div>{m['invoice_item_fa.summary.replacement_or_change']()}: <span class="text-gray-900 dark:text-gray-100">0.00000000</span></div>
            <div>{m['invoice_item_fa.summary.definitive']()}: <span class="text-gray-900 dark:text-gray-100">0.00000000</span></div>
            <div>{m['invoice_item_fa.summary.returned_values']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.value_returned_usd)}</span></div>
            <div class="col-span-2">{m['invoice_item_fa.summary.returned_values']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.value_returned_mxn)}</span></div>
        </div>
        <div class="grid grid-cols-2 gap-2 text-xs pt-2 border-t">
            <div class="font-semibold">{m['invoice_item_fa.summary.weights_kilos']()}</div>
            <div class="font-semibold">{m['invoice_item_fa.summary.weights_pounds']()}</div>
            <div>{m['invoice_item_fa.summary.net']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(quantities.net_weight)}</span></div>
            <div><span class="text-gray-900 dark:text-gray-100">0.00000000</span></div>
            <div>{m['invoice_item_fa.summary.gross']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(quantities.gross_weight)}</span></div>
            <div><span class="text-gray-900 dark:text-gray-100">0.00000000</span></div>
        </div>
    </fieldset>

<!-- COSTS AND VALUES -->
<fieldset class="border rounded-md p-2 space-y-1 bg-amber-50 dark:bg-amber-950/20">
    <legend class="text-xs font-semibold px-2 bg-amber-700 text-white">{m['invoice_item_fa.summary.costs_values']()}</legend>
	
	<div class="grid grid-cols-2 gap-2 text-xs">
        <div class="font-semibold">{m['invoice_item_fa.summary.dollars']()}</div>
        <div class="font-semibold">{m['invoice_item_fa.summary.pesos']()}</div>
        <div>{m['invoice_item_fa.summary.cost']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.unit_cost_usd)}</span></div>
		<div><span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.unit_cost_mxn)}</span></div>
        <div>{m['invoice_item_fa.summary.value']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.value_usd)}</span></div>
		<div><span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.value_mxn)}</span></div>
        <div class="text-xs">{m['invoice_item_fa.summary.customs_value']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.customs_value_usd)}</span></div>
        <div class="text-xs">{m['invoice_item_fa.summary.customs_value']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.customs_value_mxn)}</span></div>
        <div class="text-xs">{m['invoice_item_fa.summary.capture_cost']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.unit_cost_capture)}</span> <span class="text-gray-900 dark:text-gray-100">{invoiceCurrency}</span></div>
		<div></div>
        <div class="text-xs">{m['invoice_item_fa.summary.capture_value']()}: <span class="text-gray-900 dark:text-gray-100">{formatNumber(financials.value_mc)}</span> <span class="text-gray-900 dark:text-gray-100">{invoiceCurrency}</span></div>				
	</div>
</fieldset>
</div>
