let creditRecords = [];

document.addEventListener('DOMContentLoaded', async () => {
    await loadCreditRecords();
    await loadNextCustomerId();
});

// Load next available customer ID
async function loadNextCustomerId() {
    try {
        const data = await app.apiGet('/standalone-credits/next-id');
        document.getElementById('customerId').value = data.next_id;
    } catch (error) {
        console.error('Error loading next customer ID:', error);
    }
}

// Load all credit records
async function loadCreditRecords() {
    try {
        creditRecords = await app.apiGet('/standalone-credits');
        displayCreditRecords(creditRecords);
    } catch (error) {
        console.error('Error loading credit records:', error);
        app.showNotification('Failed to load credit records', 'error');
        document.getElementById('creditTableBody').innerHTML =
            '<tr><td colspan="7" class="loading">Failed to load credit records</td></tr>';
    }
}

// Display credit records in table
function displayCreditRecords(records) {
    const tbody = document.getElementById('creditTableBody');

    if (records.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="loading">No credit records found</td></tr>';
        return;
    }

    tbody.innerHTML = records.map(record => {
        const remaining = record.total_amount - record.paid_amount;
        const status = remaining === 0 ? 'Cleared' : 'Pending';
        const statusClass = remaining === 0 ? 'badge-success' : 'badge-warning';

        return `
            <tr class="fade-in">
                <td>${record.customer_id}</td>
                <td>${record.customer_name}</td>
                <td>${app.formatCurrency(record.total_amount)}</td>
                <td>${app.formatCurrency(record.paid_amount)}</td>
                <td>${app.formatCurrency(remaining)}</td>
                <td><span class="badge ${statusClass}">${status}</span></td>
                <td>
                    <button class="btn btn-primary" onclick="openEditCreditModal(${record.id})" style="padding: 0.5rem 1rem; font-size: 0.75rem; margin-right: 0.25rem;">
                        Edit
                    </button>
                    <button class="btn btn-danger" onclick="deleteCreditRecord(${record.id})" style="padding: 0.5rem 1rem; font-size: 0.75rem;">
                        Delete
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

// Add new credit record
async function addCreditRecord(event) {
    event.preventDefault();

    const customerId = document.getElementById('customerId').value;
    const customerName = document.getElementById('customerName').value;
    const totalAmount = parseFloat(document.getElementById('totalAmount').value);
    const amountPaid = parseFloat(document.getElementById('amountPaid').value) || 0;

    // Validate inputs
    if (isNaN(totalAmount) || totalAmount < 0) {
        app.showNotification('Please enter a valid total amount', 'error');
        return;
    }

    if (isNaN(amountPaid) || amountPaid < 0) {
        app.showNotification('Please enter a valid paid amount', 'error');
        return;
    }

    if (amountPaid > totalAmount) {
        app.showNotification('Paid amount cannot exceed total amount', 'error');
        return;
    }

    const creditData = {
        customer_id: parseInt(customerId),
        customer_name: customerName.trim(),
        total_amount: totalAmount,
        paid_amount: amountPaid
    };

    try {
        await app.apiPost('/standalone-credits', creditData);
        app.showNotification('Credit record added successfully', 'success');

        // Reset form
        document.getElementById('creditAddForm').reset();

        // Reload records and next customer ID
        await loadCreditRecords();
        await loadNextCustomerId();
    } catch (error) {
        console.error('Error adding credit record:', error);
        app.showNotification('Failed to add credit record: ' + (error.message || 'Unknown error'), 'error');
    }
}

// Open edit credit modal
function openEditCreditModal(recordId) {
    const record = creditRecords.find(r => r.id === recordId);
    if (!record) return;

    const remaining = record.total_amount - record.paid_amount;

    document.getElementById('editCreditId').value = record.id;
    document.getElementById('editCustomerId').value = record.customer_id;
    document.getElementById('editCustomerName').value = record.customer_name;
    document.getElementById('editTotalAmount').value = app.formatCurrency(record.total_amount);
    document.getElementById('editCurrentPaid').value = app.formatCurrency(record.paid_amount);

    // Set min value for new payment to 0 and max to remaining amount
    document.getElementById('newPaymentAmount').min = 0;
    document.getElementById('newPaymentAmount').max = remaining;
    document.getElementById('newPaymentAmount').value = '';

    document.getElementById('editCreditModal').classList.add('active');
}

// Close edit credit modal
function closeEditCreditModal() {
    document.getElementById('editCreditModal').classList.remove('active');
    document.getElementById('editCreditForm').reset();
}

// Update credit payment
async function updateCreditPayment(event) {
    event.preventDefault();

    const recordId = parseInt(document.getElementById('editCreditId').value);
    const newPaymentAmount = parseFloat(document.getElementById('newPaymentAmount').value);

    if (isNaN(newPaymentAmount) || newPaymentAmount < 0) {
        app.showNotification('Please enter a valid payment amount', 'error');
        return;
    }

    try {
        // Get current record to calculate remaining
        const currentRecord = creditRecords.find(r => r.id === recordId);
        if (!currentRecord) {
            app.showNotification('Credit record not found', 'error');
            return;
        }

        const newPaidAmount = currentRecord.paid_amount + newPaymentAmount;
        const totalAmount = currentRecord.total_amount;

        if (newPaidAmount > totalAmount) {
            app.showNotification('Total paid amount cannot exceed total amount', 'error');
            return;
        }

        const updateData = {
            paid_amount: newPaidAmount
        };

        await app.apiPut(`/standalone-credits/${recordId}`, updateData);
        app.showNotification('Credit payment updated successfully', 'success');

        closeEditCreditModal();
        await loadCreditRecords();
    } catch (error) {
        console.error('Error updating credit payment:', error);
        app.showNotification('Failed to update credit payment: ' + (error.message || 'Unknown error'), 'error');
    }
}

// Delete credit record
async function deleteCreditRecord(recordId) {
    if (!confirm('Are you sure you want to permanently delete this credit record? This action cannot be undone.')) {
        return;
    }

    try {
        await app.apiDelete(`/standalone-credits/${recordId}`);
        app.showNotification('Credit record deleted successfully', 'success');
        await loadCreditRecords();
        await loadNextCustomerId();
    } catch (error) {
        console.error('Error deleting credit record:', error);
        app.showNotification('Failed to delete credit record: ' + (error.message || 'Unknown error'), 'error');
    }
}

// Search credits
async function searchCredits() {
    const searchTerm = document.getElementById('searchInput').value.trim();

    try {
        let apiUrl = '/standalone-credits';
        if (searchTerm) {
            apiUrl += `?search=${encodeURIComponent(searchTerm)}`;
        }

        const records = await app.apiGet(apiUrl);
        displayCreditRecords(records);
    } catch (error) {
        console.error('Error searching credit records:', error);
        app.showNotification('Failed to search credit records', 'error');
    }
}

// Clear search
async function clearSearch() {
    document.getElementById('searchInput').value = '';
    await loadCreditRecords();
}

// Download PDF
function downloadCreditPDF() {
    // Create a simple PDF using jsPDF
    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF();

    // Add title
    pdf.setFontSize(18);
    pdf.text('Credit Records Report', 105, 15, null, null, 'center');

    // Add generation date
    pdf.setFontSize(12);
    pdf.text(`Generated on: ${new Date().toLocaleString()}`, 105, 25, null, null, 'center');

    // Prepare data for the table
    const headers = [['Customer ID', 'Username', 'Total Amount', 'Paid Amount', 'Remaining Amount', 'Status']];
    const data = creditRecords.map(record => {
        const remaining = record.total_amount - record.paid_amount;
        const status = remaining === 0 ? 'Cleared' : 'Pending';
        return [
            record.customer_id.toString(),
            record.customer_name,
            app.formatCurrency(record.total_amount),
            app.formatCurrency(record.paid_amount),
            app.formatCurrency(remaining),
            status
        ];
    });

    // Add table
    if (data.length > 0) {
        pdf.autoTable({
            head: headers,
            body: data,
            startY: 35,
            styles: {
                fontSize: 10,
                cellPadding: 5
            },
            headStyles: {
                fillColor: [52, 58, 64], // Dark gray
                textColor: [255, 255, 255] // White text
            }
        });
    } else {
        pdf.text('No credit records to display', 105, 45, null, null, 'center');
    }

    // Save the PDF
    pdf.save('credit_records_report.pdf');
}