/**
 * Aysa Credit Analytics JavaScript
 * Handles credit usage analytics functionality
 */

(function($) {
    'use strict';

    // Global variables
    let creditChart = null;
    let currentPage = 1;
    let totalPages = 1;
    let currentFilters = {
        transactionType: '',
        startDate: '',
        endDate: ''
    };

    // Initialize when document is ready
    $(document).ready(function() {
        console.log('Credit Analytics: Document ready');
        console.log('Credit Analytics: Localized data:', aysa_credit_analytics);
        
        // Check if required data is available
        if (typeof aysa_credit_analytics === 'undefined') {
            console.error('Credit Analytics: aysa_credit_analytics object is not defined');
            return;
        }
        
        if (!aysa_credit_analytics.ajax_url) {
            console.error('Credit Analytics: AJAX URL is missing');
            return;
        }
        
        if (!aysa_credit_analytics.nonce) {
            console.error('Credit Analytics: Nonce is missing');
            return;
        }

        // This script is enqueued broadly; only run where analytics UI exists.
        if (!$('#current-balance').length && !$('.aysa-credit-analytics').length) {
            return;
        }
        
        initializeCreditAnalytics();
    });

    /**
     * Initialize the credit analytics functionality
     */
    function initializeCreditAnalytics() {
        // Load initial data
        loadCreditData();
        
        // Set up event listeners
        setupEventListeners();
        
        // Set up auto-refresh (every 5 minutes)
        setInterval(loadCreditData, 5 * 60 * 1000);
    }
    
    // Make the function globally available
    window.initCreditAnalytics = initializeCreditAnalytics;

    /**
     * Set up event listeners for the analytics panel
     */
    function setupEventListeners() {
        // Refresh button
        $('#refresh-credit-data').on('click', function() {
            loadCreditData();
        });

        // Filter controls
        $('#apply-filters').on('click', function() {
            applyFilters();
        });

        $('#clear-filters').on('click', function() {
            clearFilters();
        });

        // Pagination controls
        $('#prev-page').on('click', function() {
            if (currentPage > 1) {
                currentPage--;
                loadTransactionHistory();
            }
        });

        $('#next-page').on('click', function() {
            if (currentPage < totalPages) {
                currentPage++;
                loadTransactionHistory();
            }
        });

        // Enter key on filter inputs
        $('.aysa-transaction-filters input, .aysa-transaction-filters select').on('keypress', function(e) {
            if (e.which === 13) { // Enter key
                applyFilters();
            }
        });
    }

    /**
     * Load all credit data
     */
    function loadCreditData() {
        showLoadingState();
        updateLastUpdatedTime();

        // Load data in parallel
        Promise.all([
            loadCreditBalance(),
            loadCreditSummary(),
            loadCreditBreakdown(),
            loadTransactionHistory(),
            loadExpiringCredits()
        ]).then(function() {
            hideLoadingState();
        }).catch(function(error) {
            console.error('Error loading credit data:', error);
            showErrorState('Failed to load credit data. Please try again.');
        });
    }

    /**
     * Load current credit balance
     */
    function loadCreditBalance() {
        return new Promise(function(resolve, reject) {
            $.ajax({
                url: aysa_credit_analytics.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_get_credit_balance',
                    nonce: aysa_credit_analytics.nonce
                },
                success: function(response) {
                    console.log('Credit balance response:', response);
                    if (response.success && response.data) {
                        // API returns totalCredits, not currentBalance
                        const balance = response.data.totalCredits || response.data.currentBalance || 0;
                        $('#current-balance').text(formatCredits(balance));
                        resolve(response.data);
                    } else {
                        console.error('Credit balance error:', response);
                        $('#current-balance').text('Error');
                        reject(new Error('Failed to load credit balance: ' + (response.data || 'Unknown error')));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Credit balance AJAX error:', xhr, status, error);
                    $('#current-balance').text('Error');
                    reject(new Error('AJAX error loading credit balance: ' + error));
                }
            });
        });
    }

    /**
     * Load credit summary (total earned, spent, etc.)
     */
    function loadCreditSummary() {
        return new Promise(function(resolve, reject) {
            $.ajax({
                url: aysa_credit_analytics.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_get_credit_summary',
                    nonce: aysa_credit_analytics.nonce
                },
                success: function(response) {
                    console.log('Credit summary response:', response);
                    if (response.success && response.data) {
                        // API returns different structure - adapt to actual response
                        $('#total-earned').text(formatCredits(response.data.totalEarned || 0));
                        $('#total-spent').text(formatCredits(response.data.totalCreditsUsed || response.data.totalSpent || 0));
                        resolve(response.data);
                    } else {
                        console.error('Credit summary error:', response);
                        $('#total-earned').text('Error');
                        $('#total-spent').text('Error');
                        reject(new Error('Failed to load credit summary'));
                    }
                },
                error: function() {
                    $('#total-earned').text('Error');
                    $('#total-spent').text('Error');
                    reject(new Error('AJAX error loading credit summary'));
                }
            });
        });
    }

    /**
     * Load credit breakdown by type
     */
    function loadCreditBreakdown() {
        return new Promise(function(resolve, reject) {
            $.ajax({
                url: aysa_credit_analytics.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_get_credit_breakdown',
                    nonce: aysa_credit_analytics.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        renderCreditBreakdownChart(response.data);
                        resolve(response.data);
                    } else {
                        showChartError();
                        reject(new Error('Failed to load credit breakdown'));
                    }
                },
                error: function() {
                    showChartError();
                    reject(new Error('AJAX error loading credit breakdown'));
                }
            });
        });
    }

    /**
     * Load expiring credits
     */
    function loadExpiringCredits() {
        return new Promise(function(resolve, reject) {
            $.ajax({
                url: aysa_credit_analytics.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_get_expiring_credits',
                    nonce: aysa_credit_analytics.nonce,
                    days_ahead: 30
                },
                success: function(response) {
                    console.log('Credit balance response:', response);
                    
                    if (response.success && response.data) {
                        let expiringAmount = 0;
                        
                        // Handle different response formats
                        if (Array.isArray(response.data)) {
                            // If it's an array, sum up the credits
                            expiringAmount = response.data.reduce(function(sum, credit) {
                                return sum + (credit.credits || 0);
                            }, 0);
                        } else if (typeof response.data === 'object') {
                            // If it's an object with array property
                            if (Array.isArray(response.data.records)) {
                                expiringAmount = response.data.records.reduce(function(sum, credit) {
                                    return sum + (credit.credits || 0);
                                }, 0);
                            } else {
                                // If it's a single object, use its value directly
                                expiringAmount = response.data.expiringCredits || response.data.credits || 0;
                            }
                        }
                        
                        $('#expiring-credits').text(formatCredits(expiringAmount));
                        resolve(response.data);
                    } else {
                        $('#expiring-credits').text('0');
                        resolve([]);
                    }
                },
                error: function() {
                    $('#expiring-credits').text('Error');
                    reject(new Error('AJAX error loading expiring credits'));
                }
            });
        });
    }

    /**
     * Load transaction history
     */
    function loadTransactionHistory() {
        return new Promise(function(resolve, reject) {
            const tbody = $('#transaction-history-tbody');
            tbody.html('<tr><td colspan="5" class="aysa-loading-cell"><span class="aysa-loading-spinner"></span> Loading transactions...</td></tr>');

            $.ajax({
                url: aysa_credit_analytics.ajax_url,
                type: 'POST',
                data: {
                    action: 'aysa_get_credit_history',
                    nonce: aysa_credit_analytics.nonce,
                    page: currentPage,
                    page_size: 20,
                    transaction_type: currentFilters.transactionType,
                    start_date: currentFilters.startDate,
                    end_date: currentFilters.endDate
                },
                success: function(response) {
                    console.log('Transaction history response:', response);
                    
                    if (response.success && response.data) {
                        // Pass the data to the rendering function
                        renderTransactionHistory(response.data);
                        
                        // Update pagination with the response data
                        updatePagination(response.data);
                        
                        resolve(response.data);
                    } else {
                        showTransactionError();
                        reject(new Error('Failed to load transaction history'));
                    }
                },
                error: function() {
                    showTransactionError();
                    reject(new Error('AJAX error loading transaction history'));
                }
            });
        });
    }

    /**
     * Render credit breakdown chart
     */
    function renderCreditBreakdownChart(data) {
        const canvas = document.getElementById('credit-breakdown-chart');
        
        // Check if canvas exists before trying to get context
        if (!canvas) {
            console.warn('Credit breakdown chart canvas not found, skipping chart rendering');
            return;
        }
        
        const ctx = canvas.getContext('2d');

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

        // Prepare chart data
        const chartData = {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: ['#4CAF50', '#2196F3', '#FF9800', '#F44336'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        };

        // Process breakdown data - API returns categoryBreakdown
        const breakdown = data.categoryBreakdown || data.creditBreakdown || [];
        if (breakdown && breakdown.length > 0) {
            breakdown.forEach(function(item, index) {
                const credits = item.credits || item.amount || 0;
                if (credits > 0) {
                    chartData.labels.push(item.type || item.category || 'Unknown');
                    chartData.datasets[0].data.push(credits);
                }
            });
        }

        // Create chart if we have data
        if (chartData.labels.length > 0) {
            creditChart = new Chart(ctx, {
                type: 'doughnut',
                data: chartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });

            // Update legend
            updateChartLegend(chartData);
        } else {
            // Show empty state
            showEmptyChart();
        }
    }

    /**
     * Update chart legend
     */
    function updateChartLegend(chartData) {
        const legendContainer = $('#credit-breakdown-legend');
        let legendHtml = '';

        chartData.labels.forEach(function(label, index) {
            const value = chartData.datasets[0].data[index];
            const color = chartData.datasets[0].backgroundColor[index];
            
            legendHtml += `
                <div class="aysa-legend-item">
                    <div class="aysa-legend-color" style="background-color: ${color}"></div>
                    <span class="aysa-legend-label">${label}</span>
                    <span class="aysa-legend-value">${formatCredits(value)}</span>
                </div>
            `;
        });

        legendContainer.html(legendHtml);
    }

    /**
     * Render transaction history table
     */
    function renderTransactionHistory(data) {
        const tbody = $('#transaction-history-tbody');
        
        // API returns records, not transactions
        // Handle both direct array and nested records array
        let transactions = [];
        
        if (Array.isArray(data)) {
            transactions = data;
        } else if (data.records && Array.isArray(data.records)) {
            transactions = data.records;
        } else if (data.transactions && Array.isArray(data.transactions)) {
            transactions = data.transactions;
        }
        
        console.log('Transaction data:', transactions);
        
        if (!transactions || transactions.length === 0) {
            tbody.html('<tr><td colspan="5" class="text-center text-muted">No transaction history available</td></tr>');
            // Show "No Credit Data" section when there are no transactions
            showEmptyChart();
            return;
        }
        
        // Hide "No Credit Data" section when we have transaction data
        const emptyChartElement = $('#credit-breakdown-legend .aysa-empty-state');
        if (emptyChartElement.length > 0) {
            emptyChartElement.hide();
        }
        
        // Get current balance for calculation
        const currentBalance = parseFloat($('#current-credits').text().replace(/[^\d.-]/g, '')) || 0;
        console.log('Current balance for calculation:', currentBalance);
        
        // Sort transactions by date (oldest first for proper balance calculation)
        transactions.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
        
        // Calculate running balance starting from current balance
        let runningBalance = currentBalance;
        const balanceHistory = [];
        
        // Calculate balance history in chronological order
        transactions.forEach(transaction => {
            const creditsUsed = parseFloat(transaction.creditsUsed || 0);
            
            // Add the transaction amount to get the balance after this transaction
            runningBalance = runningBalance + creditsUsed;
            balanceHistory.push(runningBalance);
        });
        
        // Now render the table with calculated balances
        let html = '';
        transactions.forEach((transaction, index) => {
            const date = formatTransactionDate(transaction.createdAt);
            const type = formatTransactionType(transaction.category);
            const amount = formatTransactionAmount(transaction.creditsUsed, transaction.category);
            const balanceAfter = formatBalance(balanceHistory[index]);
            
            html += `
                <tr>
                    <td>${date}</td>
                    <td><span class="badge badge-${getTransactionTypeClass(transaction.category)}">${type}</span></td>
                    <td class="text-${transaction.category === 'credit_purchase' || transaction.category === 'credit_refund' ? 'success' : 'danger'}">${amount}</td>
                    <td class="text-primary font-weight-bold">${balanceAfter}</td>
                </tr>
            `;
        });
        
        tbody.html(html);
    }

    /**
     * Update pagination controls
     */
    function updatePagination(data) {
        console.log('Pagination data:', data);
        
        // API returns page, not currentPage
        currentPage = data.page || data.currentPage || 1;
        
        // Handle different API response formats
        if (data.totalPages !== undefined) {
            // Direct totalPages property
            totalPages = data.totalPages || 1;
        } else {
            // Calculate total pages from totalCount and pageSize
            const pageSize = data.pageSize || 20;
            const totalCount = data.totalCount || 0;
            totalPages = Math.ceil(totalCount / pageSize) || 1;
        }

        $('#pagination-info').text(`Page ${currentPage} of ${totalPages}`);
        
        $('#prev-page').prop('disabled', currentPage <= 1);
        $('#next-page').prop('disabled', currentPage >= totalPages);
    }

    /**
     * Apply filters to transaction history
     */
    function applyFilters() {
        currentFilters.transactionType = $('#transaction-type-filter').val();
        currentFilters.startDate = $('#start-date-filter').val();
        currentFilters.endDate = $('#end-date-filter').val();
        
        currentPage = 1; // Reset to first page
        loadTransactionHistory();
    }

    /**
     * Clear all filters
     */
    function clearFilters() {
        $('#transaction-type-filter').val('');
        $('#start-date-filter').val('');
        $('#end-date-filter').val('');
        
        currentFilters = {
            transactionType: '',
            startDate: '',
            endDate: ''
        };
        
        currentPage = 1;
        loadTransactionHistory();
    }

    /**
     * Utility functions
     */
    function formatCredits(amount) {
        return Math.floor(amount || 0).toLocaleString();
    }

    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    }

    function formatTransactionType(type) {
        // Handle API response categories
        const categoryMap = {
            'seo configuration': 'SEO Configuration',
            'keyword research': 'Keyword Research',
            'competitor analysis': 'Competitor Analysis',
            'domain authority': 'Domain Authority',
            'backlink analysis': 'Backlink Analysis',
            'content optimization': 'Content Optimization',
            'technical seo': 'Technical SEO',
            'link building': 'Link Building',
            'analytics': 'Analytics',
            'reporting': 'Reporting',
            'automation': 'Automation',
            'api usage': 'API Usage'
        };
        
        // Also handle legacy transaction types for backward compatibility
        const typeMap = {
            'earned': 'Earned',
            'spent': 'Spent',
            'expired': 'Expired',
            'refund': 'Refund',
            'bonus': 'Bonus'
        };
        
        // Try category map first, then type map, then use original value
        const displayType = categoryMap[type] || typeMap[type] || type;
        return `<span class="aysa-transaction-type ${type}">${displayType}</span>`;
    }

    /**
     * Format transaction amount with proper sign
     */
    function formatTransactionAmount(amount, category) {
        const num = parseFloat(amount);
        if (isNaN(num)) return '0';
        
        // Determine if this is a credit addition or deduction
        const isAddition = ['credit_purchase', 'credit_refund'].includes(category);
        
        // Format the number
        const formatted = Math.abs(num).toLocaleString('en-US', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 2
        });
        
        // Add sign based on transaction type
        if (isAddition) {
            return `+${formatted}`;
        } else {
            return `-${formatted}`;
        }
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function updateLastUpdatedTime() {
        const now = new Date();
        $('#last-updated-time').text(now.toLocaleTimeString());
    }

    function showLoadingState() {
        // Loading states are handled by individual functions
    }

    function hideLoadingState() {
        // Loading states are handled by individual functions
    }

    function showErrorState(message) {
        const errorHtml = `
            <div class="aysa-error-state">
                <div class="aysa-error-state-icon">⚠️</div>
                <h5>Error Loading Data</h5>
                <p>${message}</p>
            </div>
        `;
        
        // Show error in main areas
        $('#current-balance').html('Error');
        $('#total-earned').html('Error');
        $('#total-spent').html('Error');
        $('#expiring-credits').html('Error');
    }

    function showChartError() {
        $('#credit-breakdown-legend').html(`
            <div class="aysa-error-state">
                <div class="aysa-error-state-icon">📊</div>
                <h5>Chart Error</h5>
                <p>Unable to load credit breakdown chart.</p>
            </div>
        `);
    }

    function showTransactionError() {
        $('#transaction-history-tbody').html(`
            <tr>
                <td colspan="5" class="aysa-error-state">
                    <div class="aysa-error-state-icon">⚠️</div>
                    <h5>Error Loading Transactions</h5>
                    <p>Unable to load transaction history. Please try again.</p>
                </td>
            </tr>
        `);
    }

    function showEmptyChart() {
        $('#credit-breakdown-legend').html(`
            <div class="aysa-empty-state">
                <div class="aysa-empty-state-icon">📊</div>
                <h5>No Credit Data</h5>
                <p>No credit breakdown data available.</p>
            </div>
        `);
    }

    /**
     * Format transaction date
     */
    function formatTransactionDate(dateString) {
        if (!dateString) return 'N/A';
        
        try {
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return 'Invalid Date';
            
            return date.toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (error) {
            console.error('Error formatting date:', error);
            return 'Invalid Date';
        }
    }

    /**
     * Format balance with proper number formatting
     */
    function formatBalance(balance) {
        const num = parseFloat(balance);
        if (isNaN(num)) return '0';
        
        return num.toLocaleString('en-US', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 2
        });
    }

    /**
     * Get CSS class for transaction type badge
     */
    function getTransactionTypeClass(category) {
        const typeMap = {
            'credit_purchase': 'success',
            'credit_refund': 'info',
            'api_usage': 'warning',
            'seo_analysis': 'primary',
            'keyword_research': 'secondary',
            'content_optimization': 'dark'
        };
        
        return typeMap[category] || 'secondary';
    }

})(jQuery);
