document.addEventListener('DOMContentLoaded', function() {
    const activeRate = parseFloat(document.getElementById('activeRate')?.value || 0);
    const amountInput = document.getElementById('amount');
    const billCheckboxes = document.querySelectorAll('.bill-checkbox');
    const billAmountInputs = document.querySelectorAll('.bill-amount-input');
    const selectAllCheckbox = document.getElementById('selectAllBills');
    const selectAllBtn = document.getElementById('selectAllBillsBtn');
    const deselectAllBtn = document.getElementById('deselectAllBillsBtn');
    const applyRemainingBtn = document.getElementById('applyRemainingBtn');
    
    const summaryAssignedAmount = document.getElementById('summaryAssignedAmount');
    const summaryRemainingAmount = document.getElementById('summaryRemainingAmount');
    const conversionUsd = document.getElementById('conversionUsd');

    function parseAmount(value) {
        if (!value) return 0;
        value = value.toString().trim();
        value = value.replace(/\./g, '').replace(',', '.');
        return parseFloat(value) || 0;
    }

    function formatAmount(value) {
        return value.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function updateConversion() {
        const paymentAmount = parseAmount(amountInput.value);
        const usdAmount = paymentAmount / activeRate;
        conversionUsd.textContent = formatAmount(usdAmount) + ' USD';
    }

    function updateSummary() {
        const paymentAmount = parseAmount(amountInput.value);
        let assignedAmount = 0;
        
        billAmountInputs.forEach(input => {
            if (!input.disabled) {
                assignedAmount += parseAmount(input.value);
            }
        });
        
        const remainingAmount = paymentAmount - assignedAmount;
        
        summaryAssignedAmount.textContent = formatAmount(assignedAmount) + ' Bs';
        summaryRemainingAmount.textContent = formatAmount(remainingAmount > 0 ? remainingAmount : 0) + ' Bs';
        
        updateConversion();
    }

    function getRemainingAmount() {
        const paymentAmount = parseAmount(amountInput.value);
        let assignedAmount = 0;
        
        billAmountInputs.forEach(input => {
            if (!input.disabled) {
                assignedAmount += parseAmount(input.value);
            }
        });
        
        return paymentAmount - assignedAmount;
    }

    function toggleBillSelection(checkbox, isChecked) {
        const billId = checkbox.value;
        const amountInput = document.querySelector(`.bill-amount-input[data-bill-id="${billId}"]`);
        
        checkbox.checked = isChecked;
        
        if (amountInput) {
            amountInput.disabled = !isChecked;
            if (isChecked) {
                const debt = parseFloat(checkbox.dataset.debt) || 0;
                const remaining = getRemainingAmount();
                const toAssign = Math.min(debt, Math.max(0, remaining));
                amountInput.value = toAssign > 0 ? formatAmount(toAssign) : '';
            } else {
                amountInput.value = '';
            }
        }
    }

    function selectAllBills() {
        deselectAllBills();
        billCheckboxes.forEach(checkbox => {
            const billId = checkbox.value;
            const amountInput = document.querySelector(`.bill-amount-input[data-bill-id="${billId}"]`);
            
            checkbox.checked = true;
            
            if (amountInput) {
                amountInput.disabled = false;
                const debt = parseFloat(checkbox.dataset.debt) || 0;
                const remaining = getRemainingAmount();
                const toAssign = Math.min(debt, Math.max(0, remaining));
                if (toAssign > 0) {
                    amountInput.value = formatAmount(toAssign);
                }
            }
        });
        if (selectAllCheckbox) selectAllCheckbox.checked = true;
        updateSummary();
    }

    function deselectAllBills() {
        billCheckboxes.forEach(checkbox => {
            const billId = checkbox.value;
            const amountInput = document.querySelector(`.bill-amount-input[data-bill-id="${billId}"]`);
            
            checkbox.checked = false;
            
            if (amountInput) {
                amountInput.disabled = true;
                amountInput.value = '';
            }
        });
        if (selectAllCheckbox) selectAllCheckbox.checked = false;
        updateSummary();
    }

    function applyRemainingAutomatically() {
        const paymentAmount = parseAmount(amountInput.value);
        
        if (paymentAmount <= 0) {
            Swal.fire({
                icon: 'info',
                title: 'Sin monto',
                text: 'Debes ingresar un monto de pago primero.'
            });
            return;
        }
        
        let remaining = paymentAmount;
        
        billCheckboxes.forEach(checkbox => {
            if (remaining <= 0) return;
            
            const billId = checkbox.value;
            const amountInput = document.querySelector(`.bill-amount-input[data-bill-id="${billId}"]`);
            
            if (!amountInput || amountInput.disabled) return;
            
            const debt = parseFloat(checkbox.dataset.debt) || 0;
            const toAssign = Math.min(debt, remaining);
            
            if (toAssign > 0) {
                amountInput.value = formatAmount(toAssign);
                remaining -= toAssign;
            }
        });
        
        updateSummary();
        
        if (remaining > 0.01) {
            Swal.fire({
                icon: 'info',
                title: 'Monto restante',
                html: `Aún quedan <strong>${formatAmount(remaining)} Bs</strong> sin asignar.<br>Selecciona más facturas o el pago parcial se aplicará a las facturas seleccionadas.`
            });
        }
    }

    // Event Listeners
    selectAllCheckbox?.addEventListener('change', function() {
        if (this.checked) {
            selectAllBills();
        } else {
            deselectAllBills();
        }
    });

    selectAllBtn?.addEventListener('click', selectAllBills);
    deselectAllBtn?.addEventListener('click', deselectAllBills);
    applyRemainingBtn?.addEventListener('click', applyRemainingAutomatically);

    billCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            toggleBillSelection(this, this.checked);
            updateSummary();
        });
    });

    amountInput?.addEventListener('input', function() {
        updateSummary();
    });

    billAmountInputs.forEach(input => {
        input.addEventListener('input', function() {
            const maxDebt = parseFloat(this.dataset.maxDebt) || 0;
            const value = parseAmount(this.value);
            
            if (value > maxDebt) {
                this.value = formatAmount(maxDebt);
            }
            
            updateSummary();
        });
    });

    // Validar antes de enviar
    document.getElementById('payBillForm').addEventListener('submit', function(e) {
        const paymentAmount = parseAmount(amountInput.value);
        let assignedAmount = 0;
        let hasSelectedBills = false;
        
        billCheckboxes.forEach(checkbox => {
            if (checkbox.checked) {
                hasSelectedBills = true;
                const billId = checkbox.value;
                const amountInput = document.querySelector(`.bill-amount-input[data-bill-id="${billId}"]`);
                if (amountInput && !amountInput.disabled) {
                    assignedAmount += parseAmount(amountInput.value);
                }
            }
        });

        if (!hasSelectedBills) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Sin facturas',
                text: 'Debes seleccionar al menos una factura para asociar al pago.'
            });
            return;
        }

        if (assignedAmount <= 0) {
            e.preventDefault();
            Swal.fire({
                icon: 'warning',
                title: 'Sin montos',
                text: 'Debes asignar montos a las facturas seleccionadas.'
            });
            return;
        }

        if (assignedAmount > paymentAmount) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'La suma de montos asignados no puede ser mayor al monto del pago.'
            });
            return;
        }
    });

    // Inicializar
    updateSummary();
});
