let currentReportData = null;
let currentMonthYear = '';

document.addEventListener('DOMContentLoaded', () => {
    // Show Reports link for Admin and Manager only
    const userRole = localStorage.getItem('role');
    if (userRole === 'Admin' || userRole === 'Manager') {
        const reportsLink = document.getElementById('reportsLink');
        if (reportsLink) reportsLink.style.display = 'flex';
    }

    // Set current month as default
    const today = new Date();
    const currentMonth = today.toISOString().slice(0, 7); // YYYY-MM format
    document.getElementById('monthSelector').value = currentMonth;

    // Auto-load current month report
    loadMonthlyReport();
});

async function loadMonthlyReport() {
    const monthSelector = document.getElementById('monthSelector');
    const selectedMonth = monthSelector.value;

    if (!selectedMonth) {
        app.showNotification('Please select a month', 'error');
        return;
    }

    currentMonthYear = selectedMonth;

    try {
        // Show loading state
        document.getElementById('transactionsTableBody').innerHTML =
            '<tr><td colspan="7" class="loading">Loading report...</td></tr>';

        // Fetch monthly report data
        const reportData = await app.apiGet(`/monthly-report?month_year=${selectedMonth}`);
        currentReportData = reportData;

        // Display summary
        displaySummary(reportData.summary);

        // Display transactions
        displayTransactions(reportData.transactions);

        // Enable download buttons
        document.getElementById('excelBtn').disabled = false;
        document.getElementById('pdfBtn').disabled = false;

        // Show sections
        document.getElementById('summarySection').style.display = 'grid';
        document.getElementById('transactionsSection').style.display = 'block';

        // Update month display
        const monthDate = new Date(selectedMonth + '-01');
        const monthName = monthDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
        document.getElementById('reportMonthDisplay').textContent = monthName;

    } catch (error) {
        console.error('Error loading monthly report:', error);
        app.showNotification('Failed to load monthly report', 'error');
        document.getElementById('transactionsTableBody').innerHTML =
            '<tr><td colspan="7" class="loading">Failed to load report</td></tr>';
    }
}

function displaySummary(summary) {
    const netSales = summary.total_sales - summary.total_discounts;

    document.getElementById('totalSales').textContent = app.formatCurrency(summary.total_sales);
    document.getElementById('totalTransactions').textContent = summary.total_transactions;
    document.getElementById('totalDiscounts').textContent = app.formatCurrency(summary.total_discounts);
    document.getElementById('netSales').textContent = app.formatCurrency(netSales);
}

function displayTransactions(transactions) {
    const tbody = document.getElementById('transactionsTableBody');

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

    tbody.innerHTML = transactions.map(transaction => {
        const finalTotal = transaction.total_amount - (transaction.discount_amount || 0);
        const itemsCount = transaction.items.length;
        const itemsSummary = itemsCount === 1
            ? `${transaction.items[0].product_name} (${transaction.items[0].quantity})`
            : `${itemsCount} items`;

        return `
            <tr class="fade-in">
                <td>${app.formatDate(transaction.transaction_date)}</td>
                <td>${transaction.customer_name}</td>
                <td><span class="badge badge-${transaction.payment_type.toLowerCase()}">${transaction.payment_type}</span></td>
                <td>${itemsSummary}</td>
                <td>${app.formatCurrency(transaction.total_amount)}</td>
                <td class="text-success">${transaction.discount_percentage > 0 ? `-${transaction.discount_percentage}% (${app.formatCurrency(transaction.discount_amount)})` : '-'}</td>
                <td><strong>${app.formatCurrency(finalTotal)}</strong></td>
            </tr>
        `;
    }).join('');
}

function downloadExcelReport() {
    if (!currentReportData) {
        app.showNotification('No report data available', 'error');
        return;
    }

    try {
        // Create workbook
        const wb = XLSX.utils.book_new();

        // Summary Sheet
        const summaryData = [
            ['Monthly Sales Report'],
            ['Month:', currentMonthYear],
            ['Generated:', new Date().toLocaleString()],
            [],
            ['Summary'],
            ['Total Sales:', currentReportData.summary.total_sales],
            ['Total Transactions:', currentReportData.summary.total_transactions],
            ['Total Discounts:', currentReportData.summary.total_discounts],
            ['Net Sales:', currentReportData.summary.total_sales - currentReportData.summary.total_discounts],
        ];
        const summarySheet = XLSX.utils.aoa_to_sheet(summaryData);
        XLSX.utils.book_append_sheet(wb, summarySheet, 'Summary');

        // Transactions Sheet
        const transactionsData = [
            ['Date', 'Customer', 'Payment Type', 'Items', 'Subtotal', 'Discount %', 'Discount Amount', 'Final Total']
        ];

        currentReportData.transactions.forEach(transaction => {
            const finalTotal = transaction.total_amount - (transaction.discount_amount || 0);
            const itemsList = transaction.items.map(item =>
                `${item.product_name} ${item.flavour} (${item.weight}) x${item.quantity}`
            ).join('; ');

            transactionsData.push([
                transaction.transaction_date,
                transaction.customer_name,
                transaction.payment_type,
                itemsList,
                transaction.total_amount,
                transaction.discount_percentage || 0,
                transaction.discount_amount || 0,
                finalTotal
            ]);
        });

        const transactionsSheet = XLSX.utils.aoa_to_sheet(transactionsData);
        XLSX.utils.book_append_sheet(wb, transactionsSheet, 'Transactions');

        // Detailed Items Sheet
        const itemsData = [
            ['Date', 'Transaction ID', 'Customer', 'Product', 'Flavour', 'Weight', 'Quantity', 'Unit Price', 'Subtotal']
        ];

        currentReportData.transactions.forEach(transaction => {
            transaction.items.forEach(item => {
                itemsData.push([
                    transaction.transaction_date,
                    transaction.id,
                    transaction.customer_name,
                    item.product_name,
                    item.flavour,
                    item.weight,
                    item.quantity,
                    item.unit_price,
                    item.subtotal
                ]);
            });
        });

        const itemsSheet = XLSX.utils.aoa_to_sheet(itemsData);
        XLSX.utils.book_append_sheet(wb, itemsSheet, 'Detailed Items');

        // Download file
        const fileName = `Monthly_Report_${currentMonthYear}.xlsx`;
        XLSX.writeFile(wb, fileName);

        app.showNotification('Excel report downloaded successfully', 'success');
    } catch (error) {
        console.error('Error generating Excel report:', error);
        app.showNotification('Failed to generate Excel report', 'error');
    }
}

function downloadPDFReport() {
    if (!currentReportData) {
        app.showNotification('No report data available', 'error');
        return;
    }

    try {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();

        // Title
        doc.setFontSize(20);
        doc.text('Monthly Sales Report', 14, 20);

        // Month and date
        doc.setFontSize(12);
        const monthDate = new Date(currentMonthYear + '-01');
        const monthName = monthDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
        doc.text(`Month: ${monthName}`, 14, 30);
        doc.text(`Generated: ${new Date().toLocaleString()}`, 14, 37);

        // Summary section
        doc.setFontSize(14);
        doc.text('Summary', 14, 50);

        doc.setFontSize(11);
        const netSales = currentReportData.summary.total_sales - currentReportData.summary.total_discounts;
        doc.text(`Total Sales: PKR ${currentReportData.summary.total_sales.toLocaleString()}`, 14, 58);
        doc.text(`Total Transactions: ${currentReportData.summary.total_transactions}`, 14, 65);
        doc.text(`Total Discounts: PKR ${currentReportData.summary.total_discounts.toLocaleString()}`, 14, 72);
        doc.text(`Net Sales: PKR ${netSales.toLocaleString()}`, 14, 79);

        // Transactions table
        doc.setFontSize(14);
        doc.text('Transactions', 14, 92);

        const tableData = currentReportData.transactions.map(transaction => {
            const finalTotal = transaction.total_amount - (transaction.discount_amount || 0);
            const itemsCount = transaction.items.length;

            return [
                transaction.transaction_date,
                transaction.customer_name,
                transaction.payment_type,
                itemsCount.toString(),
                `PKR ${transaction.total_amount.toLocaleString()}`,
                transaction.discount_percentage > 0 ? `${transaction.discount_percentage}%` : '-',
                `PKR ${finalTotal.toLocaleString()}`
            ];
        });

        doc.autoTable({
            startY: 97,
            head: [['Date', 'Customer', 'Payment', 'Items', 'Subtotal', 'Discount', 'Final Total']],
            body: tableData,
            theme: 'striped',
            headStyles: { fillColor: [37, 99, 235] },
            styles: { fontSize: 9 },
            columnStyles: {
                0: { cellWidth: 25 },
                1: { cellWidth: 35 },
                2: { cellWidth: 20 },
                3: { cellWidth: 15 },
                4: { cellWidth: 30 },
                5: { cellWidth: 20 },
                6: { cellWidth: 30 }
            }
        });

        // Add detailed items on new page if there are transactions
        if (currentReportData.transactions.length > 0) {
            doc.addPage();
            doc.setFontSize(14);
            doc.text('Detailed Items', 14, 20);

            const detailedData = [];
            currentReportData.transactions.forEach(transaction => {
                transaction.items.forEach(item => {
                    detailedData.push([
                        transaction.transaction_date,
                        transaction.customer_name,
                        `${item.product_name} ${item.flavour}`,
                        item.weight,
                        item.quantity.toString(),
                        `PKR ${item.unit_price.toLocaleString()}`,
                        `PKR ${item.subtotal.toLocaleString()}`
                    ]);
                });
            });

            doc.autoTable({
                startY: 25,
                head: [['Date', 'Customer', 'Product', 'Weight', 'Qty', 'Price', 'Subtotal']],
                body: detailedData,
                theme: 'striped',
                headStyles: { fillColor: [37, 99, 235] },
                styles: { fontSize: 8 },
                columnStyles: {
                    0: { cellWidth: 25 },
                    1: { cellWidth: 30 },
                    2: { cellWidth: 40 },
                    3: { cellWidth: 20 },
                    4: { cellWidth: 15 },
                    5: { cellWidth: 25 },
                    6: { cellWidth: 25 }
                }
            });
        }

        // Download PDF
        const fileName = `Monthly_Report_${currentMonthYear}.pdf`;
        doc.save(fileName);

        app.showNotification('PDF report downloaded successfully', 'success');
    } catch (error) {
        console.error('Error generating PDF report:', error);
        app.showNotification('Failed to generate PDF report', 'error');
    }
}
