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

  function updateFileCounters() {
    $.post(mindwecoFiles.ajax_url, {
      action: 'mindweco_get_stats_files',
      nonce: mindwecoFiles.nonce
    }).done(function(response) {
      if (response.success) {
        $('#indexed-count-files').text(response.data.indexed);
        $('#to-index-count-files').text(response.data.to_index);
        $('#index-progress-files').text(response.data.progress + '%');
      }
    }).fail(function() {
      MindwecoToast.error('Failed to update file counters');
    });
  }

  $('.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-files') {
      loadIndexedTableFiles(true);
    }
    if (tab === 'indexing-files') {
      updateFileCounters();
    }
  });

  (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-files' && typeof loadIndexedTableFiles === 'function') {
        loadIndexedTableFiles();
      }
      if (tab === 'indexing-files') {
        updateFileCounters();
      }
    }
  })();

  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-files').html(str);
    displayRows();
  }

  function displayRows() {
    var table = document.getElementById('table-indexed-files');
    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-files');
    if (!table) return;
    var numRows = table.getElementsByTagName('tr').length - 1;
    var numPages = Math.ceil(numRows / rowsPerPage);
    createPagination(numPages, currentPage);
  }

  function loadIndexedTableFiles(forceReload) {

    if (tableLoaded && !forceReload) {
      return;
    }

    tableLoaded = true;

    var $tbody = $('#table-indexed-files tbody');
    $tbody.html('<tr><td colspan="10">Loading...</td></tr>');

    $.post(mindwecoFiles.ajax_url, {
        action: 'mindweco_get_indexed_table_files',
        nonce: mindwecoFiles.nonce
      })
      .done(function(response) {
        if (response.success) {
          if (response.data && response.data.trim().length > 0) {
            $tbody.html(response.data);

            MindwecoToast.success('Indexed files loaded successfully');
            refreshPagination();
          } else {
            MindwecoToast.warning('No data returned from server');

            $tbody.html('<tr><td colspan="10">No indexed files found.</td></tr>');
            MindwecoToast.warning('No indexed files yet. Start indexing to see files here.');
          }
        } else {
          MindwecoToast.error('Response success = false', response);

          $tbody.html('<tr><td colspan="10">Failed to load.</td></tr>');
          MindwecoToast.error('Failed to load indexed files (server returned error)');
        }
      })
      .fail(function(xhr, status, error) {
        MindwecoToast.error('AJAX failed:', {
          xhr,
          status,
          error
        });

        tableLoaded = false;

        MindwecoToast.error('AJAX error while loading indexed files');
        $tbody.html('<tr><td colspan="10">AJAX error.</td></tr>');
      });

    $('#search-input-files').val('').trigger('keyup');
  }

  $('#search-input-files').on('keyup', function() {
    var value = $(this).val().toLowerCase().trim();
    var visibleCount = 0;

    if (value.length > 0) {
      $('#pagination-files').hide();
    } else {
      $('#pagination-files').show();
      refreshPagination();
      return;
    }

    $('#table-indexed-files 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-files tbody').append(
          '<tr id="no-search-result"><td colspan="10" class="text-center text-muted">No matching files found.</td></tr>'
        );
      }
    } else {
      $('#no-search-result').remove();
    }
  });

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

  $('#mindweco-index-all-files').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%');
    var postData = {
      action: 'mindweco_index_all_media_files',
      nonce: mindwecoFiles.nonce
    };

    $.post(mindwecoFiles.ajax_url, postData)
      .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[data-tab="manage-files"]').trigger('click');

          setTimeout(updateFileCounters, 500);
          setTimeout(updateFileCounters, 1500);
          setTimeout(updateFileCounters, 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.file_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-file', 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(mindwecoFiles.ajax_url, {
        action: 'mindweco_delete_indexed_file',
        nonce: mindwecoFiles.nonce,
        item_id: item_id,
        category_id: category_id
      }).done(function(response) {
        if (response.success) {
          MindwecoToast.success(response.data.message || 'File unindexed successfully');
          $row.fadeOut(300, function() {
            $row.remove();
            updateFileCounters();
            refreshPagination();
            var $tbody = $('#table-indexed-files tbody');
            if ($tbody.find('tr').length === 0) {
              $tbody.html('<tr><td colspan="10">No indexed files 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-files').on('click', function() {
    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-files');
      $result.html('<i class="fas fa-spinner fa-spin" style="margin-right:5px;"></i> Unindexing all files...').show();
      $.post(mindwecoFiles.ajax_url, {
        action: 'mindweco_unindex_all_files',
        nonce: mindwecoFiles.nonce
      }, function(response) {
        if (response.success) {
          tableLoaded = false;
          $('#table-indexed-files tbody').html('<tr><td colspan="10">No indexed files found.</td></tr>');
          updateFileCounters();
          $progressBar.removeClass('mindweco-progress-active').addClass('mindweco-progress-empty');
          $progressBar.css('width', '0%');
          $progressText.text('0%');
          setTimeout(function() {
            MindwecoToast.success('All files have been unindexed.');
            $result.text(response.data.message);
            setTimeout(function() {
              $result.fadeOut(1000);
            }, 3000);
          }, 1500);
          $('.nav-tab[data-tab="indexing-files"]').click();
          $('#mindweco-index-all-result').hide();
        } else {
          MindwecoToast.error('Error unindexing all files.');
          $result.fadeOut(1000);
        }
      });
    }, 'Unindex', 'btn-danger');
  });

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

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


  if (typeof wp !== 'undefined' && wp.Uploader) {
    var originalSuccess = wp.Uploader.prototype.success;
    wp.Uploader.prototype.success = function(attachment) {
      if (originalSuccess) originalSuccess.call(this, attachment);

      var mime = attachment.get('mime');
      var supported = [
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ];
      if (supported.indexOf(mime) === -1) return;

      var attachmentId = attachment.get('id');
      var attempts = 0;
      var maxAttempts = 6;

      function pollForIndexing() {
        attempts++;
        $.post(mindwecoFiles.ajax_url, {
          action: 'mindweco_check_file_indexed',
          nonce: mindwecoFiles.nonce,
          file_id: attachmentId
        }).done(function(response) {
          if (response.success && response.data.indexed) {
            updateFileCounters();
            if (tableLoaded) loadIndexedTableFiles(true);
            MindwecoToast.success('New file indexed successfully!');
          } else if (attempts < maxAttempts) {
            setTimeout(pollForIndexing, 5000);
          } else {
            MindwecoToast.warning('File uploaded but indexing may still be in progress.');
            updateFileCounters();
          }
        }).fail(function() {
          if (attempts < maxAttempts) setTimeout(pollForIndexing, 5000);
        });
      }

      setTimeout(pollForIndexing, 4000);
    };
  }

});