jQuery(document).ready(function($) {
    var searchTPSavedTokens = function(e) {
        e.preventDefault();
        
        var formData = {
            action: 'remove_payment_token',
            action_type: 'search',
            nonce: wcTokenRemoval.nonce,
            customer_email: $('#customer_email').val(),
            card_last_four: $('#card_last_four').val(),
            issuing_bank: $('#issuing_bank').val()
        };
        
        $.ajax({
            url: wcTokenRemoval.ajax_url,
            type: 'POST',
            data: formData,
            beforeSend: function() {
                $('#search-results').hide();
                $('.button-primary').prop('disabled', true).val('Searching...');
            },
            success: function(response) {
                if (response.success && response.data.tokens) {
                    displaySearchResults(response.data);
                } else {
                    alert('Error: ' + response.data.error);
                }
            },
            error: function() {
                alert('Ajax request failed');
            },
            complete: function() {
                $('.button-primary').prop('disabled', false).val('Search Tokens');
            }
        });
    };

    $('#search-tp-saved-token').on('click', searchTPSavedTokens );

    $('.search-tp-saved-token-avoidenterpress').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { searchTPSavedTokens(e); return; }
    });
    
    function displaySearchResults(data) {
        var html = '';
        
        if (data.tokens.length === 0) {
            html = '<p>No matching tokens found.</p>';
        } else {
            html = '<table class="wp-list-table widefat fixed striped">';
            html += '<thead><tr><th>Token ID</th><th>Type</th><th>Last 4</th><th>Gateway</th><th>Created</th><th>Action</th></tr></thead>';
            html += '<tbody>';
            
            data.tokens.forEach(function(token) {
                html += '<tr>';
                html += '<td>' + token.token_id + '</td>';
                html += '<td>' + token.token_type + '</td>';
                html += '<td>' + token.last4 + '</td>';
                html += '<td>' + token.gateway_title + '</td>';
                html += '<td>' + token.created_date + '</td>';
                html += '<td><button class="button button-secondary remove-token" data-token-id="' + token.token_id + '">Remove</button></td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
        }
        
        $('#tokens-list').html(html);
        $('#search-results').show();
    }
    
    $(document).on('click', '.remove-token', function() {
        if (!confirm(wcTokenRemoval.confirm_text)) {
            return;
        }
        
        var tokenId = $(this).data('token-id');
        var $button = $(this);
        
        var formData = {
            action: 'remove_payment_token',
            action_type: 'remove',
            nonce: wcTokenRemoval.nonce,
            token_id: tokenId,
            customer_email: $('#customer_email').val(),
            card_last_four: $('#card_last_four').val()
        };
        
        $.ajax({
            url: wcTokenRemoval.ajax_url,
            type: 'POST',
            data: formData,
            beforeSend: function() {
                $button.prop('disabled', true).text('Removing...');
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').fadeOut();
                    addToLog('Success: ' + response.data);
                } else {
                    alert('Error: ' + response.data);
                    addToLog('Error: ' + response.data);
                }
            },
            error: function() {
                alert('Ajax request failed');
                addToLog('Ajax request failed for token ID: ' + tokenId);
            },
            complete: function() {
                $button.prop('disabled', false).text('Remove');
            }
        });
    });
    
    function addToLog(message) {
        var timestamp = new Date().toLocaleString();
        var logEntry = '<p><strong>' + timestamp + ':</strong> ' + message + '</p>';
        
        $('#log-content').prepend(logEntry);
        $('#removal-log').show();
    }
});
