(function($) {
    'use strict';
    
    const ReportsDashboard = {
        init: function() {
            this.initDatePickers();
            this.initFilters();
            this.initCharts();
            this.loadData();
            this.initEventListeners();
        },
        
        initDatePickers: function() {
            if ($.fn.datepicker) {
                $('.irandargah-datepicker').datepicker({
                    dateFormat: 'yy/mm/dd',
                    changeMonth: true,
                    changeYear: true,
                    showButtonPanel: true
                });
            }
            
            $('#time-range').on('change', function() {
                if ($(this).val() === 'custom') {
                    $('#custom-date-range').show();
                } else {
                    $('#custom-date-range').hide();
                }
            });
        },
        
        initFilters: function() {
            $('#apply-filters').on('click', () => {
                this.loadData();
            });
        },
        
        initCharts: function() {
            // Initialize Chart.js charts
            this.initTrendChart();
            this.initGatewaysShareChart();
            this.initSuccessRateChart();
            this.initRevenueChart();
        },
        
        initTrendChart: function() {
            const ctx = document.getElementById('transactions-trend-chart');
            if (!ctx) return;
            
            this.trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'موفق',
                        data: [],
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'ناموفق',
                        data: [],
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'معلق',
                        data: [],
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                            rtl: true
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        },
        
        initGatewaysShareChart: function() {
            const ctx = document.getElementById('gateways-share-chart');
            if (!ctx) return;
            
            this.gatewaysShareChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: [
                            '#3b82f6',
                            '#10b981',
                            '#f59e0b',
                            '#ef4444',
                            '#8b5cf6',
                            '#ec4899',
                            '#06b6d4',
                            '#84cc16'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            rtl: true
                        }
                    }
                }
            });
        },
        
        initSuccessRateChart: function() {
            const ctx = document.getElementById('success-rate-chart');
            if (!ctx) return;
            
            this.successRateChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'نرخ موفقیت (%)',
                        data: [],
                        backgroundColor: '#10b981'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
        },
        
        initRevenueChart: function() {
            const ctx = document.getElementById('revenue-chart');
            if (!ctx) return;
            
            this.revenueChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'درآمد (تومان)',
                        data: [],
                        backgroundColor: '#3b82f6'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        },
        
        loadData: function() {
            const timeRange = $('#time-range').val();
            const gateway = $('#gateway-filter').val();
            const dateFrom = $('#date-from').val();
            const dateTo = $('#date-to').val();
            
            $.ajax({
                url: irandargahReports.ajax_url,
                type: 'POST',
                data: {
                    action: 'irandargah_reports_data',
                    nonce: irandargahReports.nonce,
                    time_range: timeRange,
                    gateway: gateway,
                    date_from: dateFrom,
                    date_to: dateTo
                },
                success: (response) => {
                    if (response.success) {
                        this.updateStats(response.data.stats);
                        this.updateCharts(response.data.charts);
                    }
                },
                error: () => {
                    console.error('Error loading reports data');
                }
            });
        },
        
        updateStats: function(stats) {
            $('#total-successful').text(this.formatNumber(stats.successful));
            $('#total-failed').text(this.formatNumber(stats.failed));
            $('#total-pending').text(this.formatNumber(stats.pending));
            $('#total-revenue').text(this.formatCurrency(stats.revenue));
        },
        
        updateCharts: function(charts) {
            if (this.trendChart && charts.trend) {
                this.trendChart.data.labels = charts.trend.labels || [];
                this.trendChart.data.datasets[0].data = charts.trend.successful || [];
                this.trendChart.data.datasets[1].data = charts.trend.failed || [];
                this.trendChart.data.datasets[2].data = charts.trend.pending || [];
                this.trendChart.update();
            }
            
            if (this.gatewaysShareChart && charts.gateways_share) {
                this.gatewaysShareChart.data.labels = charts.gateways_share.labels || [];
                this.gatewaysShareChart.data.datasets[0].data = charts.gateways_share.data || [];
                this.gatewaysShareChart.update();
            }
            
            if (this.successRateChart && charts.success_rate) {
                this.successRateChart.data.labels = charts.success_rate.labels || [];
                this.successRateChart.data.datasets[0].data = charts.success_rate.data || [];
                this.successRateChart.update();
            }
            
            if (this.revenueChart && charts.revenue) {
                this.revenueChart.data.labels = charts.revenue.labels || [];
                this.revenueChart.data.datasets[0].data = charts.revenue.data || [];
                this.revenueChart.update();
            }
        },
        
        initEventListeners: function() {
            // Export transactions
            $('#export-transactions').on('click', () => {
                this.exportTransactions();
            });
            
            // Transaction search
            $('#transaction-search').on('keyup', (e) => {
                if (e.key === 'Enter') {
                    this.loadTransactions();
                }
            });
            
            // Status filter
            $('#transaction-status-filter').on('change', () => {
                this.loadTransactions();
            });
        },
        
        loadTransactions: function() {
            const search = $('#transaction-search').val();
            const status = $('#transaction-status-filter').val();
            
            $.ajax({
                url: irandargahReports.ajax_url,
                type: 'POST',
                data: {
                    action: 'irandargah_transactions',
                    nonce: irandargahReports.nonce,
                    search: search,
                    status: status
                },
                success: (response) => {
                    if (response.success) {
                        this.renderTransactions(response.data.transactions);
                    }
                }
            });
        },
        
        renderTransactions: function(transactions) {
            const tbody = $('#transactions-tbody');
            tbody.empty();
            
            if (transactions.length === 0) {
                tbody.html('<tr><td colspan="7" class="irandargah-loading">' + irandargahReports.strings.no_data + '</td></tr>');
                return;
            }
            
            transactions.forEach(transaction => {
                const statusClass = transaction.status === 'success' ? 'success' : 
                                   transaction.status === 'failed' ? 'failed' : 'pending';
                const statusText = transaction.status === 'success' ? 'موفق' : 
                                  transaction.status === 'failed' ? 'ناموفق' : 'معلق';
                
                const row = `
                    <tr>
                        <td>${transaction.id}</td>
                        <td>${transaction.customer_name}</td>
                        <td>${this.formatCurrency(transaction.amount)}</td>
                        <td>${transaction.gateway}</td>
                        <td><span class="irandargah-status-badge ${statusClass}">${statusText}</span></td>
                        <td>${transaction.date}</td>
                        <td>
                            <button class="irandargah-btn irandargah-btn-secondary" onclick="ReportsDashboard.viewTransaction('${transaction.id}')">
                                مشاهده
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        },
        
        exportTransactions: function() {
            // TODO: Implement CSV export
            alert('قابلیت خروجی CSV به زودی اضافه خواهد شد.');
        },
        
        formatNumber: function(num) {
            return new Intl.NumberFormat('fa-IR').format(num);
        },
        
        formatCurrency: function(amount) {
            return new Intl.NumberFormat('fa-IR', {
                style: 'currency',
                currency: 'IRR',
                minimumFractionDigits: 0
            }).format(amount);
        },
        
        viewTransaction: function(id) {
            // TODO: Implement transaction detail view
            console.log('View transaction:', id);
        }
    };
    
    $(document).ready(function() {
        ReportsDashboard.init();
    });
    
    // Make ReportsDashboard globally available
    window.ReportsDashboard = ReportsDashboard;
    
})(jQuery);



