jQuery(document).ready(function($) {
    // Initialize date range
    const from = $('#from').val();
    const to = $('#to').val();

    // Load all data
    loadDashboardData(from, to);

    // Handle date filter form submission
    $('.ads-date-filter form').on('submit', function(e) {
        e.preventDefault();
        const from = $('#from').val();
        const to = $('#to').val();
        loadDashboardData(from, to);
    });

    function loadDashboardData(from, to) {
        if (!$('.ads-date-filter').length) {
            return;
        }

        $.ajax({
            url: ads_analytics.ajax_url,
            type: 'POST',
            data: {
                action: 'ads_get_analytics_data',
                nonce: ads_analytics.nonce,
                from: from,
                to: to
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    // Update summary cards
                    $('#total-incomplete-orders').text(data.total_incomplete);
                    // Replace the two cards with the new one
                    $('#total-recovery-orders').text(data.total_recovery_orders);
                    $('#recovery-rate').text(data.recovery_rate + '%');
                    $('#recovery-amount').text(ads_analytics.currency_symbol + parseFloat(data.recovery_amount).toFixed(2));

                    // Render incomplete orders by day chart
                    renderIncompleteOrdersChart(data.incomplete_by_day);

                    // Render orders by status chart
                    renderOrdersByStatusChart(data.orders_by_status);

                    // Update top recovery days table
                    updateTopRecoveryDaysTable(data.top_recovery_days);
                }
            }
        });
    }

    function renderIncompleteOrdersChart(data) {
        const ctx = document.getElementById('incomplete-orders-chart').getContext('2d');

        // Destroy existing chart if it exists
        if (window.incompleteOrdersChart) {
            window.incompleteOrdersChart.destroy();
        }

        window.incompleteOrdersChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.labels,
                datasets: [{
                    label: 'Incomplete Orders',
                    data: data.data,
                    borderColor: '#4e73df',
                    backgroundColor: 'rgba(78, 115, 223, 0.05)',
                    borderWidth: 2,
                    pointBackgroundColor: '#4e73df',
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgb(255, 255, 255)',
                        bodyColor: '#858796',
                        titleColor: '#6e707e',
                        borderColor: '#dddfeb',
                        borderWidth: 1,
                        padding: 10,
                        displayColors: false,
                        caretPadding: 10,
                        callbacks: {
                            label: function(context) {
                                return 'Orders: ' + context.parsed.y;
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false,
                            drawBorder: false
                        },
                        ticks: {
                            maxRotation: 0,
                            autoSkip: true,
                            maxTicksLimit: 7
                        }
                    },
                    y: {
                        grid: {
                            color: 'rgb(234, 236, 244)',
                            drawBorder: false,
                            borderDash: [2],
                            zeroLineBorderDash: [2]
                        },
                        ticks: {
                            beginAtZero: true,
                            padding: 10
                        }
                    }
                }
            }
        });
    }

    function renderOrdersByStatusChart(data) {
        const ctx = document.getElementById('orders-by-status-chart').getContext('2d');

        // Destroy existing chart if it exists
        if (window.ordersByStatusChart) {
            window.ordersByStatusChart.destroy();
        }

        window.ordersByStatusChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: data.labels,
                datasets: [{
                    data: data.data,
                    backgroundColor: data.backgroundColors,
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            padding: 15,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgb(255, 255, 255)',
                        bodyColor: '#858796',
                        titleColor: '#6e707e',
                        borderColor: '#dddfeb',
                        borderWidth: 1,
                        padding: 10,
                        displayColors: false,
                        caretPadding: 10,
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.parsed;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return label + ': ' + value + ' (' + percentage + '%)';
                            }
                        }
                    }
                },
                cutout: '70%'
            }
        });
    }

    function updateTopRecoveryDaysTable(data) {
        let html = '';

        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                const day = data[i];
                html += '<tr>';
                html += '<td>' + day.recovery_date + '</td>';
                html += '<td>' + day.recovered_carts + '</td>';
                html += '<td>' + ads_analytics.currency_symbol + parseFloat(day.recovered_revenue).toFixed(2) + '</td>';
                html += '</tr>';
            }
        } else {
            html = '<tr><td colspan="3">No data available</td></tr>';
        }

        console.log(html);

        $('#top-recovery-days-tbody').html(html);
    }
});