(function ($) {
    'use strict';

    let usageTrendsChart = null;
    let discountsChart = null;

    $(document).ready(function () {
        if (typeof unlockafeReportingData === 'undefined') {
            console.error('UNLOCKAFE: Reporting data not loaded');
            return;
        }

        // Debug: Log chart data
        console.log('UNLOCKAFE: Chart data loaded', unlockafeReportingData);

        // Initialize charts
        initializeCharts();

        // Date range quick filters
        $('.quick-filter').on('click', function(e) {
            e.preventDefault();
            const days = $(this).data('days');
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(endDate.getDate() - days);

            $('#start-date').val(formatDate(startDate));
            $('#end-date').val(formatDate(endDate));
            
            // Use setTimeout to ensure DOM is updated before validation
            setTimeout(function() {
                updateChartsWithMessage(days);
            }, 10);
        });

        // Update charts button
        $('#update-charts').on('click', updateCharts);

        // Export CSV button
        $('#export-report').on('click', exportCSV);

        // Create test data button
        $('#create-test-data').on('click', createTestData);
    });

    function initializeCharts() {
        // Usage Trends Chart
        var usageTrendsCtx = document.getElementById('unlockafeUsageTrendsChart');
        if (usageTrendsCtx) {
            console.log('UNLOCKAFE: Initializing Usage Trends Chart');
            usageTrendsChart = new Chart(usageTrendsCtx, {
                type: 'line',
                data: {
                    labels: unlockafeReportingData.usage_trends.labels,
                    datasets: [{
                        label: 'Coupon Usage',
                        data: unlockafeReportingData.usage_trends.data,
                        borderColor: 'rgba(102, 126, 234, 1)',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: 'rgba(102, 126, 234, 1)',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        pointHoverRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    aspectRatio: 2,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                color: 'rgba(0,0,0,0.05)'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.05)'
                            }
                        }
                    }
                }
            });
        }

        // Discounts Over Time Chart
        var discountsCtx = document.getElementById('unlockafeDiscountsOverTimeChart');
        if (discountsCtx) {
            console.log('UNLOCKAFE: Initializing Discounts Chart');
            try {
                discountsChart = new Chart(discountsCtx, {
                type: 'bar',
                data: {
                    labels: unlockafeReportingData.discounts_over_time.labels,
                    datasets: [{
                        label: 'Discount Amount',
                        data: unlockafeReportingData.discounts_over_time.data,
                        backgroundColor: 'rgba(245, 87, 108, 0.8)',
                        borderColor: 'rgba(245, 87, 108, 1)',
                        borderWidth: 0,
                        borderRadius: 8,
                        borderSkipped: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    aspectRatio: 2,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.05)'
                            }
                        }
                    }
                }
            });
            console.log('UNLOCKAFE: Discounts Chart initialized successfully');
            } catch (error) {
                console.error('UNLOCKAFE: Error initializing Discounts Chart:', error);
            }
        } else {
            console.error('UNLOCKAFE: Discounts chart canvas not found');
        }
    }

    function updateCharts() {
        const startDate = $('#start-date').val();
        const endDate = $('#end-date').val();

        if (!startDate || !endDate) {
            return;
        }

        // Show loading states
        $('.chart-loading').show();
        $('.table-loading').show();

        $.ajax({
            url: unlockafeReportingData.ajax_url,
            type: 'POST',
            data: {
                action: 'unlockafe_get_chart_data',
                nonce: unlockafeReportingData.nonce,
                start_date: startDate,
                end_date: endDate
            },
            success: function(response) {
                console.log('UNLOCKAFE: AJAX Response:', response);
                if (response.success) {
                    // Update charts
                    if (usageTrendsChart && response.data.usage_trends) {
                        usageTrendsChart.data.labels = response.data.usage_trends.labels;
                        usageTrendsChart.data.datasets[0].data = response.data.usage_trends.data;
                        usageTrendsChart.update('active');
                    }

                    if (discountsChart && response.data.discounts_over_time) {
                        discountsChart.data.labels = response.data.discounts_over_time.labels;
                        discountsChart.data.datasets[0].data = response.data.discounts_over_time.data;
                        discountsChart.update('active');
                    }

                    // Update summary cards
                    if (response.data.summary) {
                        console.log('UNLOCKAFE: Updating summary cards with:', response.data.summary);
                        updateSummaryCards(response.data.summary);
                    } else {
                        console.error('UNLOCKAFE: No summary data in response');
                    }

                    // Update top coupons table
                    if (response.data.top_coupons) {
                        updateTopCouponsTable(response.data.top_coupons);
                    }
                } else {
                    console.error('UNLOCKAFE: AJAX request failed:', response);
                }
            },
            error: function() {
                // Error connecting to server
            },
            complete: function() {
                // Hide loading states
                $('.chart-loading').hide();
                $('.table-loading').hide();
            }
        });
    }

    function updateChartsWithMessage(days) {
        const startDate = $('#start-date').val();
        const endDate = $('#end-date').val();

        if (!startDate || !endDate || startDate.trim() === '' || endDate.trim() === '') {
            return;
        }

        // Show loading states
        $('.chart-loading').show();
        $('.table-loading').show();

        $.ajax({
            url: unlockafeReportingData.ajax_url,
            type: 'POST',
            data: {
                action: 'unlockafe_get_chart_data',
                nonce: unlockafeReportingData.nonce,
                start_date: startDate,
                end_date: endDate
            },
            success: function(response) {
                if (response.success) {
                    // Check if data is available
                    const hasUsageData = response.data.usage_trends && response.data.usage_trends.data && response.data.usage_trends.data.some(value => value > 0);
                    const hasDiscountData = response.data.discounts_over_time && response.data.discounts_over_time.data && response.data.discounts_over_time.data.some(value => value > 0);
                    const hasTopCoupons = response.data.top_coupons && response.data.top_coupons.length > 0;

                    // Show appropriate message based on data availability
                    if (!hasUsageData && !hasDiscountData && !hasTopCoupons) {
                        showNoDataMessage(days);
                    } else {
                        hideNoDataMessage();
                    }

                    // Update charts
                    if (usageTrendsChart && response.data.usage_trends) {
                        usageTrendsChart.data.labels = response.data.usage_trends.labels;
                        usageTrendsChart.data.datasets[0].data = response.data.usage_trends.data;
                        usageTrendsChart.update('active');
                    }

                    if (discountsChart && response.data.discounts_over_time) {
                        discountsChart.data.labels = response.data.discounts_over_time.labels;
                        discountsChart.data.datasets[0].data = response.data.discounts_over_time.data;
                        discountsChart.update('active');
                    }

                    // Update summary cards
                    if (response.data.summary) {
                        updateSummaryCards(response.data.summary);
                    }

                    // Update top coupons table
                    if (response.data.top_coupons) {
                        updateTopCouponsTable(response.data.top_coupons);
                    }
                } else {
                    // Error updating charts
                }
            },
            error: function() {
                // Error connecting to server
            },
            complete: function() {
                // Hide loading states
                $('.chart-loading').hide();
                $('.table-loading').hide();
            }
        });
    }

    function updateSummaryCards(summary) {
        console.log('UNLOCKAFE: updateSummaryCards called with:', summary);
        console.log('UNLOCKAFE: Elements found:', {
            totalUsage: $('#total-usage').length,
            totalDiscount: $('#total-discount').length,
            avgDiscount: $('#avg-discount').length,
            topCoupon: $('#top-coupon').length
        });
        
        $('#total-usage').text(summary.total_coupons || '0');
        $('#total-discount').text(summary.total_discount || '$0.00');
        $('#avg-discount').text(summary.average_discount || '$0.00');
        $('#top-coupon').text(summary.most_used_coupon || 'N/A');
        
        console.log('UNLOCKAFE: Summary cards updated');
    }

    function updateTopCouponsTable(coupons) {
        const tbody = $('#top-coupons-table tbody');
        tbody.empty();

        if (coupons && coupons.length > 0) {
            coupons.forEach(function(coupon) {
                const row = `
                    <tr>
                        <td>${coupon.coupon_code}</td>
                        <td>${coupon.usage_count}</td>
                        <td>${coupon.total_discount}</td>
                        <td>${coupon.avg_discount}</td>
                    </tr>
                `;
                tbody.append(row);
            });
        } else {
            tbody.append('<tr><td colspan="4" style="text-align: center; color: #666;">No data available for selected date range</td></tr>');
        }
    }

    function exportCSV() {
        const startDate = $('#start-date').val();
        const endDate = $('#end-date').val();

        if (!startDate || !endDate) {
            alert('Please select both start and end dates before exporting.');
            return;
        }

        // Validate date range
        if (new Date(startDate) > new Date(endDate)) {
            alert('Start date cannot be later than end date.');
            return;
        }

        // Show loading state on button
        const $exportBtn = $('#export-report');
        const originalText = $exportBtn.text();
        $exportBtn.text('Exporting...').prop('disabled', true);

        // Create a form and submit it to trigger download
        const form = $('<form>', {
            method: 'POST',
            action: unlockafeReportingData.ajax_url
        });

        form.append($('<input>', {
            type: 'hidden',
            name: 'action',
            value: 'unlockafe_export_report'
        }));

        form.append($('<input>', {
            type: 'hidden',
            name: 'nonce',
            value: unlockafeReportingData.nonce
        }));

        form.append($('<input>', {
            type: 'hidden',
            name: 'start_date',
            value: startDate
        }));

        form.append($('<input>', {
            type: 'hidden',
            name: 'end_date',
            value: endDate
        }));

        form.append($('<input>', {
            type: 'hidden',
            name: 'format',
            value: 'csv'
        }));

        form.appendTo('body').submit().remove();

        // Reset button state after a short delay
        setTimeout(function() {
            $exportBtn.text(originalText).prop('disabled', false);
        }, 2000);
    }

    function formatDate(date) {
        return date.toISOString().split('T')[0];
    }


    function showNoDataMessage(days) {
        let message = '';
        let period = '';
        
        switch(days) {
            case 7:
                period = 'last 7 days';
                break;
            case 30:
                period = 'last 30 days';
                break;
            case 90:
                period = 'last 90 days';
                break;
            default:
                period = `last ${days} days`;
        }
        
        message = `No coupon data available for the ${period}. This could mean no coupons were used during this period.`;
        
        // Remove existing message if any
        $('.no-data-message').remove();
        
        // Create and show the message
        const messageHtml = `
            <div class="no-data-message" style="
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px;
                border-radius: 12px;
                margin: 20px 0;
                text-align: center;
                font-size: 16px;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
                border: 1px solid rgba(255, 255, 255, 0.2);
                backdrop-filter: blur(10px);
                animation: fadeIn 0.5s ease-in-out;
            ">
                <i class="fas fa-info-circle" style="margin-right: 10px; font-size: 18px;"></i>
                ${message}
            </div>
        `;
        
        // Insert the message after the date controls
        $('.date-controls').after(messageHtml);
        
        // Add CSS animation if not already added
        if (!$('#no-data-animation-css').length) {
            $('head').append(`
                <style id="no-data-animation-css">
                    @keyframes fadeIn {
                        from { opacity: 0; transform: translateY(-10px); }
                        to { opacity: 1; transform: translateY(0); }
                    }
                </style>
            `);
        }
    }

    function hideNoDataMessage() {
        $('.no-data-message').fadeOut(300, function() {
            $(this).remove();
        });
    }

})(jQuery);
