jQuery(document).ready(function($) {
  var tableLoaded = false;
  var rowsPerPage = 20;
  var currentPage = 1;

  function updateCounters() {
    $.post(mindwecoProductCatalog.ajax_url, {
      action: 'mindweco_get_stats_product_catalog',
      nonce: mindwecoProductCatalog.nonce
    }).done(function(response) {
      if (response.success) {
        $('#to-index-count-products').text(response.data.to_index);
        $('#indexed-count-products').text(response.data.indexed);
        $('#index-progress-products').text(response.data.progress + '%');
      }
    }).fail(function(xhr, status, error) {});
  }

  $('.nav-tab').on('click', function(e) {
    e.preventDefault();
    $('.nav-tab').removeClass('nav-tab-active');
    $(this).addClass('nav-tab-active');
    var tab = $(this).data('tab');
    $('.tab-content').hide();
    $('#tab-' + tab).show();
    if (tab === 'manage-product') {
      loadIndexedTableProducts(true);
    }
    if (tab === 'indexing-product') {
      updateCounters();
    }
  });

  (function showInitialActiveTab() {
    var $active = $('.nav-tab.nav-tab-active');
    var tab = $active.data('tab') || $('.nav-tab').first().data('tab');
    if (tab) {
      $('.tab-content').hide();
      $('#tab-' + tab).show();
      if (tab === 'manage-product' && typeof loadIndexedTableProducts === 'function') {
        loadIndexedTableProducts();
      }
      if (tab === 'indexing-product') {
        updateCounters();
      }
    }
  })();

  function createPagination(pages, page) {
    currentPage = page;
    let str = `<div class="mindweco-pagination-container">`;

    if (page > 1) {
      str += `<button class="mindweco-page-previous" data-page="${page - 1}">Previous</button>`;
    }

    let start = 1;
    let end = pages;

    if (pages > 8) {
      start = Math.max(page - 2, 1);
      end = Math.min(page + 2, pages);
      if (start > 1) {
        str += `<button class="mindweco-page-item" data-page="1">1</button>`;
        if (start > 2) {
          str += `<span class="mindweco-page-ellipsis">...</span>`;
        }
      }
    }

    for (let p = start; p <= end; p++) {
      let active = page === p ? 'mindweco-page-active' : '';
      str += `<button class="mindweco-page-item ${active}" data-page="${p}">${p}</button>`;
    }

    if (pages > 8 && end < pages) {
      if (end < pages - 1) {
        str += `<span class="mindweco-page-ellipsis">...</span>`;
      }
      str += `<button class="mindweco-page-item" data-page="${pages}">${pages}</button>`;
    }

    if (page < pages) {
      str += `<button class="mindweco-page-next" data-page="${page + 1}">Next</button>`;
    }

    str += `</div>`;

    $('#pagination').html(str);
    displayRows();
  }

  function displayRows() {
    var table = document.getElementById('table-indexed-products');
    if (!table) return;
    var rows = table.getElementsByTagName('tr');
    var numRows = rows.length - 1;
    for (var i = 1; i <= numRows; i++) {
      rows[i].style.display = 'none';
    }
    var start = (currentPage - 1) * rowsPerPage + 1;
    var end = Math.min(currentPage * rowsPerPage, numRows);
    for (var i = start; i <= end; i++) {
      if (rows[i]) rows[i].style.display = '';
    }
  }

  function refreshPagination() {
    var table = document.getElementById('table-indexed-products');
    if (!table) return;
    var numRows = table.getElementsByTagName('tr').length - 1;
    var numPages = Math.ceil(numRows / rowsPerPage);
    createPagination(numPages, currentPage);
  }

  function loadIndexedTableProducts(forceReload) {
    if (tableLoaded && !forceReload) return;
    tableLoaded = true;
    var $tbody = $('#table-indexed-products tbody');
    $tbody.html('<tr><td colspan="10">Loading...</td></tr>');
    $.post(mindwecoProductCatalog.ajax_url, {
      action: 'mindweco_get_indexed_table_products',
      nonce: mindwecoProductCatalog.nonce
    }).done(function(response) {
      if (response.success) {
        if (response.data && response.data.trim().length > 0) {
          $tbody.html(response.data);
          MindwecoToast.success('Indexed items loaded successfully');
          refreshPagination();
        } else {
          $tbody.html('<tr><td colspan="10">No indexed items found.</td></tr>');
          MindwecoToast.warning('No indexed items yet. Start indexing to see items here.');
        }
      } else {
        $tbody.html('<tr><td colspan="10">Failed to load.</td></tr>');
        MindwecoToast.error('Failed to load indexed items');
      }
    }).fail(function(xhr, status, error) {
      tableLoaded = false;
      MindwecoToast.error('Failed to load indexed items');
      $tbody.html('<tr><td colspan="10">AJAX error.</td></tr>');
    });
    $('#search-input').val('').trigger('keyup');
  }

  $('#search-input').on('keyup', function() {
    var value = $(this).val().toLowerCase().trim();
    var visibleCount = 0;
    $('#table-indexed-products tbody tr').each(function() {
      var titleText = $(this).find('td:nth-child(6)').text().toLowerCase();
      if (titleText.includes(value)) {
        $(this).show();
        visibleCount++;
      } else {
        $(this).hide();
      }
    });
    if (visibleCount === 0) {
      if ($('#no-search-result').length === 0) {
        $('#table-indexed-products tbody').append('<tr id="no-search-result"><td colspan="10" class="text-center text-muted">No matching products found.</td></tr>');
      }
    } else {
      $('#no-search-result').remove();
    }
  });

  $(document).on('click', '#pagination button', function(e) {
    e.preventDefault();
    var page = parseInt($(this).data('page'));
    if (page) {
      var table = document.getElementById('table-indexed-products');
      if (!table) return;
      var numRows = table.getElementsByTagName('tr').length - 1;
      var numPages = Math.ceil(numRows / rowsPerPage);
      createPagination(numPages, page);
    }
  });

  $('#mindweco-index-all-products').off('click').on('click', function(e) {
    e.preventDefault();
    var $button = $(this);
    var $resultDiv = $('#mindweco-index-all-result');
    var $progressContainer = $('#progress-container');
    var $progressBar = $('#progress-bar');
    var $progressText = $('#progress-text');
    $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin text-white"></span> <span class="spinner-text text-white">Indexing...</span>');
    $progressContainer.show();
    $resultDiv.html('');
    $progressBar.removeClass('mindweco-progress-active').addClass('mindweco-progress-empty');
    $progressBar.css('width', '0%');
    $progressText.text('0%');
    $.post(mindwecoProductCatalog.ajax_url, {
      action: 'mindweco_index_all_products',
      nonce: mindwecoProductCatalog.nonce
    }).done(function(response) {
      if (response.success) {
        var results = response.data;
        var total = results.length;
        var success = results.filter(function(r) {
          return r.status === 'success';
        }).length;
        var already_indexed = results.filter(function(r) {
          return r.status === 'already_indexed';
        }).length;
        var failed = results.filter(function(r) {
          return r.status === 'failed';
        }).length;
        $progressBar.css('width', '100%').removeClass('progress-empty').addClass('progress-active');
        $progressText.text('100%');
        $('.nav-tab').removeClass('nav-tab-active');
        $('.nav-tab[data-tab="manage-product"]').addClass('nav-tab-active');
        $('.tab-content').hide();
        $('#tab-manage-product').show();
        loadIndexedTableProducts(true);
        setTimeout(updateCounters, 500);
        setTimeout(updateCounters, 1500);
        setTimeout(updateCounters, 3000);
        var html = '<div class="mindweco-result-success">';
        html += '<h3 class="indexing-complete-text"><i class="fa fa-check-circle text-success"></i> Indexing Complete!</h3>';
        html += '<p class="mindweco-paragraph-complete"><strong>Total:</strong> ' + total + '</p>';
        html += '<p class="mindweco-paragraph-complete"><strong>Success:</strong> <span class = "mindweco-success-element ">' + success + '</span></p>';
        html += '<p class="mindweco-paragraph-complete"><strong>Already Indexed:</strong> <span class = "mindweco-already-indexed-element ">' + already_indexed + '</span></p>';
        html += '<p class="mindweco-paragraph-complete"><strong>Failed:</strong> <span class = "mindweco-failed-element">' + failed + '</span></p>';
        html += '</div>';
        html += '<details class="mt-3"><summary class ="fw-bold pe-auto">View Details</summary>';
        html += '<table class="wp-list-table widefat fixed striped mt-2">';
        html += '<thead><tr><th>Post ID</th><th>Title</th><th>Item ID</th><th>Status</th></tr></thead><tbody>';
        results.forEach(function(item) {
          var statusColor = item.status === 'failed' ? '#dc3232' : item.status === 'success' ? '#46b450' : '#0073aa';
          var statusIcon = item.status === 'failed' ? '<i class="fa fa-times-circle text-danger"></i>' : item.status === 'success' ? '<i class="fa fa-check-circle text-success"></i>' : item.status === 'already_indexed' ? '<i class="fa fa-circle"></i>' : '<i class="fa fa-circle-notch fa-spin"></i>';
          html += '<tr>';
          html += '<td>' + (item.post_id || 'N/A') + '</td>';
          html += '<td>' + (item.title || 'N/A') + '</td>';
          html += '<td>' + (item.item_id || 'N/A') + '</td>';
          html += '<td style="color:' + statusColor + ';font-weight:bold;">' + statusIcon + ' ' + item.status + '</td>';
          html += '</tr>';
        });
        html += '</tbody></table></details>';
        $resultDiv.html(html);
      } else {
        MindwecoToast.error('Indexing failed.');
      }
    }).fail(function() {
      MindwecoToast.error('AJAX request failed.');
    }).always(function() {
      $button.prop('disabled', false).html('<span class="dashicons dashicons-update text-white"></span> Start Indexing');
    });
  });

  $(document).on('click', '.unindex-product', function(e) {
    e.preventDefault();
    e.stopPropagation();
    var button = $(this);
    var item_id = button.data('item-id');
    var category_id = button.data('category-id');
    var $row = button.closest('tr');
    if (!item_id || !category_id) {
      MindwecoToast.error('Missing item_id or category_id');
      return;
    }
    MindwecoModal.confirm('Confirm Unindex', 'Are you sure you want to unindex this product?', function() {
      var originalHtml = button.html();
      button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Unindexing...');
      $.post(mindwecoProductCatalog.ajax_url, {
        action: 'mindweco_delete_indexed_products',
        nonce: mindwecoProductCatalog.nonce,
        item_id: item_id,
        category_id: category_id
      }).done(function(response) {
        if (response.success) {
          MindwecoToast.success(response.data.message || 'Product unindexed successfully');
          $row.fadeOut(300, function() {
            $row.remove();
            updateCounters();
            refreshPagination();
            var $tbody = $('#table-indexed-products tbody');
            if ($tbody.find('tr').length === 0) {
              $tbody.html('<tr><td colspan="10">No indexed items found.</td></tr>');
            }
          });
        } else {
          MindwecoToast.error(response.data.message || 'Error unindexing product');
          button.prop('disabled', false).html(originalHtml);
        }
      }).fail(function(xhr, status, error) {
        MindwecoToast.error('AJAX request failed');
        button.prop('disabled', false).html(originalHtml);
      });
    }, 'Unindex', 'btn-danger');
  });

  $('#mindweco-unindex-all-products').on('click', function() {
    var $button = $(this);
    var originalHtml = $button.html();
    var $progressBar = $('#progress-bar');
    var $progressText = $('#progress-text');

    MindwecoModal.confirm('Confirm Unindex', 'Are you sure you want to unindex all products?', function() {
      var $result = $('#mindweco-unindex-result');

      $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Unindexing...');
      $result.html('<i class="fas fa-spinner fa-spin" style="margin-right:5px;"></i> Unindexing all products...').show();

      $.post(mindwecoProductCatalog.ajax_url, {
        action: 'mindweco_unindex_all_products',
        nonce: mindwecoProductCatalog.nonce
      }).done(function(response) {
        if (response.success) {
          tableLoaded = false;
          $('#table-indexed-products tbody').html('<tr><td colspan="10">No indexed products found.</td></tr>');
          updateCounters();
          $progressBar.removeClass('mindweco-progress-active').addClass('mindweco-progress-empty');
          $progressBar.css('width', '0%');
          $progressText.text('0%');

          setTimeout(function() {
            MindwecoToast.success('All products have been unindexed.');
            $result.text(response.data.message);
            setTimeout(function() {
              $result.fadeOut(1000);
            }, 3000);
          }, 1500);

          $('.nav-tab[data-tab="indexing-product"]').click();
          $('#mindweco-index-all-result').empty().hide();
          $('#progress-container').hide();
        } else {
          MindwecoToast.error(response.data.message || 'Error unindexing all products.');
          $result.text(response.data.message || 'Error unindexing all products.').show();
        }
      }).fail(function() {
        MindwecoToast.error('AJAX request failed.');
        $result.text('AJAX request failed.').show();
      }).always(function() {
        $button.prop('disabled', false).html(originalHtml);
      });
    }, 'Unindex', 'btn-danger');
  });

  $(document).on('click', '.btn-index-items', function() {
    $('.nav-tab[data-tab="indexing-product"]').click();
  });

  $(document).on('click', '.submitdelete', function() {
    setTimeout(function() {
      updateCounters();
    }, 2000);
  });

});
