$(document).ready(function() {
    let isProcessing = false;

    function showProcessingOverlay(show) {
        isProcessing = show;
        const overlay = $('#processing-overlay');
        show ? overlay.fadeIn(100) : overlay.fadeOut(100);
    }

    function loadPage(pageName, callback) {
        if (isProcessing) return;
        let url = `/quanlybanhang/modules/pos/tabs/${pageName}_tab.php`;
        $('#main-content').load(url, function(response, status, xhr) {
            if (status === "error") {
                $(this).html("<p class='text-center text-danger p-3'>Lỗi tải trang.</p>");
                return;
            }
            if (callback) callback();
        });
        $('.nav-item').removeClass('active');
        $(`.nav-item[data-page="${pageName}"]`).addClass('active');
    }

    function initOverviewPage() {}

    function initInvoicesPage() {
        const filterForm = $('#invoice-filter-form');
        if (filterForm.length) {
            filterForm.on('submit', function(e) {
                e.preventDefault();
                if (isProcessing) return;
                const fromDate = $(this).find('input[name="from"]').val();
                const toDate = $(this).find('input[name="to"]').val();
                let url = `/quanlybanhang/modules/pos/tabs/invoices_tab.php?from=${fromDate}&to=${toDate}`;

                showProcessingOverlay(true);
                $('#main-content').load(url, function(response, status, xhr) {
                    showProcessingOverlay(false);
                    if (status === "error") {
                        $(this).html("<p class='text-center text-danger p-3'>Lỗi khi tải dữ liệu hóa đơn.</p>");
                        return;
                    }
                    initInvoicesPage();
                });
            });
        }
    }

    function initProfitPage() {
        const lineChartCanvas = document.getElementById('profitLineChart');
        if (lineChartCanvas && typeof Chart !== 'undefined' && window.profitChartData) {
            new Chart(lineChartCanvas, {
                type: 'line',
                data: {
                    labels: window.profitChartData.labels,
                    datasets: [{
                        label: 'Lợi nhuận',
                        data: window.profitChartData.data,
                        fill: true,
                        backgroundColor: 'rgba(25, 135, 84, 0.1)',
                        borderColor: 'rgba(25, 135, 84, 1)',
                        tension: 0.3,
                        pointBackgroundColor: 'rgba(25, 135, 84, 1)'
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return ' Lợi nhuận: ' + new Intl.NumberFormat('vi-VN').format(context.raw) + ' đ';
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            ticks: {
                                callback: function(value) {
                                    return new Intl.NumberFormat('vi-VN', { notation: 'compact' }).format(value);
                                }
                            }
                        }
                    }
                }
            });
        }
        const doughnutChartCanvas = document.getElementById('profitDoughnutChart');
        if (doughnutChartCanvas && typeof Chart !== 'undefined') {
            const profit = parseFloat(doughnutChartCanvas.dataset.profit) || 0;
            const cost = parseFloat(doughnutChartCanvas.dataset.cost) || 0;
            new Chart(doughnutChartCanvas, {
                type: 'doughnut',
                data: {
                    labels: ['Lợi nhuận', 'Tiền vốn'],
                    datasets: [{
                        data: [profit, cost],
                        backgroundColor: ['rgba(25, 135, 84, 0.9)', 'rgba(108, 117, 125, 0.7)'],
                        borderColor: ['#fff', '#fff'],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    cutout: '70%',
                    plugins: {
                        legend: { display: true, position: 'bottom', labels: { padding: 20 } },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let total = context.chart.getDatasetMeta(0).total;
                                    let percentage = total > 0 ? (context.raw / total * 100).toFixed(1) : 0;
                                    return ` ${context.label}: ${new Intl.NumberFormat('vi-VN').format(context.raw)} đ (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }
        $('#btn-filter-profit').on('click', function() {
            if (isProcessing) return;
            const fromDate = $('#profit_from_date').val();
            const toDate = $('#profit_to_date').val();
            let url = `/quanlybanhang/modules/pos/tabs/profit_tab.php?from=${fromDate}&to=${toDate}`;
            showProcessingOverlay(true);
            $('#main-content').load(url, function(response, status) {
                showProcessingOverlay(false);
                if (status === "error") {
                    $(this).html("<p class='text-center text-danger p-3'>Lỗi khi tải dữ liệu.</p>");
                    return;
                }
                initProfitPage();
            });
        });
    }

    $('.bottom-nav').on('click', '.nav-item', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if ($(this).hasClass('active') || isProcessing || !page) return;

        const initializers = {
            'overview': initOverviewPage,
            'invoices': initInvoicesPage,
            'profit': initProfitPage
        };

        if (initializers[page]) {
            loadPage(page, initializers[page]);
        }
    });

    loadPage('overview', initOverviewPage);
});