jQuery(document).ready(function($) {
    function attachEventListeners() {
        $('.edit-translation').off('click').on('click', function() {
            var row = $(this).closest('tr');
            row.find('.translation-display').hide();
            row.find('.translation-edit').show();
            row.find('.edit-translation').hide();
            row.find('.save-translation, .cancel-edit').show();
        });

        $('.cancel-edit').off('click').on('click', function() {
            var row = $(this).closest('tr');
            row.find('.translation-display').show();
            row.find('.translation-edit').hide();
            row.find('.edit-translation').show();
            row.find('.save-translation, .cancel-edit').hide();
        });

        $('.save-translation').off('click').on('click', function() {
            var row = $(this).closest('tr');
            var translationId = row.attr('id').replace('translation-', '');
            var newTranslation = row.find('.translation-edit').val();

            $.ajax({
                url: fluentcTranslations.ajaxurl,
                type: 'POST',
                data: {
                    action: 'fluentc_inline_edit',
                    translation_id: translationId,
                    new_translation: newTranslation,
                    fluentc_nonce: fluentcTranslations.nonce
                },
                success: function(response) {
                    if (response.success) {
                        row.find('.translation-display').text(newTranslation).show();
                        row.find('.translation-edit').hide();
                        row.find('.edit-translation').show();
                        row.find('.save-translation, .cancel-edit').hide();
                    } else {
                        alert('Failed to update translation: ' + response.data);
                    }
                },
                error: function() {
                   // alert('An error occurred while updating the translation');
                }
            });
        });

        $('.delete-translation').off('click').on('click', function() {
            var row = $(this).closest('tr');
            var translationId = row.attr('id').replace('translation-', '');
            
            if (confirm('Are you sure you want to delete this translation?')) {
                $.ajax({
                    url: fluentcTranslations.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'fluentc_delete_translation',
                        translation_id: translationId,
                        fluentc_nonce: fluentcTranslations.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            row.fadeOut(400, function() {
                                $(this).remove();
                            });
                        } else {
                            alert('Failed to delete translation: ' + response.data);
                        }
                    },
                    error: function() {
                      //  alert('An error occurred while deleting the translation');
                    }
                });
            }
        });
    }
    
    var currentPage = 1;
    var searchTerm = '';
    var isSearchActive = false;

    $('#translation-search-form').on('submit', function(e) {
        e.preventDefault();
        searchTerm = $('#translation-search').val();
        currentPage = 1;
        isSearchActive = true;
        performSearch();
    });

    $('#clear-search').on('click', function() {
        searchTerm = '';
        currentPage = 1;
        isSearchActive = false;
        $('#translation-search').val('');
        $(this).hide();
        loadDefaultTranslations();
    });

    function performSearch() {
        $('#search-loading').show();
        $('#translations-table').css('opacity', '0.5');

        $.ajax({
            url: fluentcTranslations.ajaxurl,
            type: 'POST',
            data: {
                action: 'fluentc_search_translations',
                search: searchTerm,
                page: currentPage,
                fluentc_nonce: fluentcTranslations.nonce
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.translations.length > 0) {
                        updateTable(response.data.translations);
                    } else {
                        showNoResults();
                    }
                    $('#clear-search').show();
                    updatePagination(response.data);
                } else {
                    alert('Search failed: ' + response.data);
                }
            },
            error: function() {
                //alert('An error occurred while searching');
            },
            complete: function() {
                $('#search-loading').hide();
                $('#translations-table').css('opacity', '1');
            }
        });
    }

    function updateTable(translations) {
        var tableBody = $('#translations-table tbody');
        tableBody.empty();

        translations.forEach(function(translation) {
            var row = `
                <tr id="translation-${translation.id}">
                    <td>${translation.sourceLanguage}</td>
                    <td>${translation.targetLanguage}</td>
                    <td>${translation.originalText}</td>
                    <td class="translation-text">
                        <span class="translation-display">${translation.translatedText}</span>
                        <input type="text" class="translation-edit" value="${translation.translatedText}" style="display: none;">
                    </td>
                    <td>
                        <button class="button edit-translation">Edit</button>
                        <button class="button save-translation" style="display: none;">Save</button>
                        <button class="button cancel-edit" style="display: none;">Cancel</button>
                        <button class="button delete-translation">Delete</button>
                    </td>
                </tr>
            `;
            tableBody.append(row);
        });
        
        attachEventListeners(); // Reattach event listeners after updating the table
    }

    function loadDefaultTranslations() {
        $('#search-loading').show();
        $('#translations-table').css('opacity', '0.5');

        $.ajax({
            url: fluentcTranslations.ajaxurl,
            type: 'POST',
            data: {
                action: 'fluentc_get_translations',
                page: currentPage,
                fluentc_nonce: fluentcTranslations.nonce
            },
            success: function(response) {
                if (response.success) {
                    updateTable(response.data.translations);
                    updatePagination(response.data);
                } else {
                    alert('Failed to load translations: ' + response.data);
                }
            },
            error: function() {
               // alert('An error occurred while loading translations');
            },
            complete: function() {
                $('#search-loading').hide();
                $('#translations-table').css('opacity', '1');
            }
        });
    }

    function showNoResults() {
        var tableBody = $('#translations-table tbody');
        tableBody.empty();
        tableBody.append('<tr><td colspan="5">No results found</td></tr>');
    }

    function updatePagination(data) {
        var totalPages = data.totalPages;
        var currentPage = data.page;
        
        if (totalPages <= 1) {
            $('#pagination').empty();
            return;
        }
    
        var paginationHtml = '<div class="tablenav bottom"><div class="tablenav-pages">';
        
        function addLink(page, text, classes) {
            if (page < 1 || page > totalPages) {
                return `<span class="tablenav-pages-navspan button disabled" aria-hidden="true">${text}</span>`;
            }
            return `<a class="page-numbers ${classes}" href="#" data-page="${page}">${text}</a>`;
        }
    
        // Previous button
        paginationHtml += addLink(currentPage - 1, '‹', 'prev-page');
    
        var startPage = Math.max(1, currentPage - 2);
        var endPage = Math.min(totalPages, startPage + 4);
        startPage = Math.max(1, endPage - 4);
    
        if (startPage > 1) {
            paginationHtml += addLink(1, '1', '');
            if (startPage > 2) {
                paginationHtml += '<span class="page-numbers dots">…</span>';
            }
        }
    
        for (var i = startPage; i <= endPage; i++) {
            if (i === currentPage) {
                paginationHtml += `<span aria-current="page" class="page-numbers current">${i}</span>`;
            } else {
                paginationHtml += addLink(i, i, '');
            }
        }
    
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHtml += '<span class="page-numbers dots">…</span>';
            }
            paginationHtml += addLink(totalPages, totalPages, '');
        }
    
        // Next button
        paginationHtml += addLink(currentPage + 1, '›', 'next-page');
    
        paginationHtml += '</div></div>';
        
        $('#pagination').html(paginationHtml);
    }

    $(document).on('click', '#pagination a.page-numbers', function(e) {
        e.preventDefault();
        currentPage = $(this).data('page');
        if (isSearchActive) {
            performSearch();
        } else {
            loadDefaultTranslations();
        }
    });

    loadDefaultTranslations();
    attachEventListeners(); // Attach event listeners on initial load
});