(function ($) {
  "use strict";

  $(function () {
    // History Search
    let searchTimer;
    $("#ai-magic-history-search").on("keyup", function () {
      clearTimeout(searchTimer);
      const searchTerm = $(this).val();

      searchTimer = setTimeout(function () {
        $.ajax({
          url: ai_magic_admin.ajax_url,
          type: "POST",
          data: {
            action: "ai_magic_search_history",
            nonce: ai_magic_admin.nonce,
            search: searchTerm,
          },
          beforeSend: function () {
            $(".wp-list-table tbody").css("opacity", "0.5");
          },
          success: function (response) {
            if (response.success) {
              $(".wp-list-table tbody").html(response.data.html);
            }
          },
          complete: function () {
            $(".wp-list-table tbody").css("opacity", "1");
          },
        });
      }, 500);
    });

    // Delete History Item
    $(document).on("click", ".ai-magic-delete-btn", function (e) {
      e.preventDefault();
      if (!confirm("Are you sure you want to delete this item?")) return;

      const btn = $(this);
      const id = btn.data("id");

      $.ajax({
        url: ai_magic_admin.ajax_url,
        type: "POST",
        data: {
          action: "ai_magic_delete_history",
          nonce: ai_magic_admin.nonce,
          id: id,
        },
        success: function (response) {
          if (response.success) {
            btn.closest("tr").fadeOut(function () {
              $(this).remove();
            });
          } else {
            alert("Failed to delete item");
          }
        },
      });
    });

    // View History Item (Modal)
    const modal = $("#ai-magic-view-modal");
    const closeBtn = $(".ai-magic-close");

    $(document).on("click", ".ai-magic-view-btn", function (e) {
      e.preventDefault();
      const btn = $(this);
      const id = btn.data("id");

      $.ajax({
        url: ai_magic_admin.ajax_url,
        type: "POST",
        data: {
          action: "ai_magic_get_history_details",
          nonce: ai_magic_admin.nonce,
          id: id,
        },
        success: function (response) {
          if (response.success) {
            const item = response.data;
            $("#ai-magic-modal-title").text(item.title || "Content Details");
            $("#ai-magic-modal-prompt").text(item.prompt);
            $("#ai-magic-modal-content").text(item.content);
            modal.fadeIn(200);
          }
        },
      });
    });

    closeBtn.on("click", function () {
      modal.fadeOut(200);
    });

    $(window).on("click", function (e) {
      if ($(e.target).is(modal)) {
        modal.fadeOut(200);
      }
    });

    // Test API Connection
    $(document).on("click", ".ai-magic-btn-test-icon", function (e) {
      e.preventDefault();
      const btn = $(this);
      const provider = btn.data("provider");
      const apiKeyInput = $("#ai_magic_api_key_" + provider);
      const resultDiv = $("#ai-magic-test-result-" + provider);
      const $icon = btn.find('.dashicons');
      const originalIconClass = $icon.attr('class');

      const apiKey = apiKeyInput.val();

      if (!apiKey) {
        alert("Please enter an API Key first.");
        return;
      }

      // Spin the icon
      $icon.attr('class', 'dashicons dashicons-update spin');
      resultDiv.hide().removeClass("error success").html("");

      // Simplified connection test prompt
      const testPrompt = "Hello, confirm connection.";

      $.ajax({
        url: ai_magic_admin.ajax_url,
        type: "POST",
        data: {
          action: "ai_magic_test_api",
          nonce: aiMagicSettings.settingsNonce,
          provider: provider,
          prompt: testPrompt
        },
        success: function (response) {
          if (response.success) {
            btn.addClass("success").removeClass("error");
            resultDiv.addClass("success").html('<span class="dashicons dashicons-yes"></span> Connection successful!').fadeIn();
            setTimeout(function () { resultDiv.fadeOut(); }, 5000);
          } else {
            btn.addClass("error").removeClass("success");
            resultDiv.addClass("error").html('<span class="dashicons dashicons-warning"></span> ' + (response.data || "Error")).fadeIn();
          }
        },
        error: function () {
          btn.addClass("error").removeClass("success");
          resultDiv.addClass("error").html('<span class="dashicons dashicons-warning"></span> Connection failed.').fadeIn();
        },
        complete: function () {
          // Restore original icon
          $icon.attr('class', originalIconClass);
        },
      });
    });

    // Fetch Models Logic
    $(".ai-magic-fetch-models-btn").on("click", function (e) {
      e.preventDefault();
      const btn = $(this);
      const provider = btn.data("provider");
      const list = $("#ai-magic-dynamic-models-" + provider);
      const apiKeyInput = $("#ai_magic_api_key_" + provider);
      const originalText = btn.html();

      // Retrieve API key to send with request
      const apiKey = apiKeyInput.val();

      btn.html('<span class="dashicons dashicons-update spin"></span> Fetching...');
      btn.prop("disabled", true);

      $.ajax({
        url: ai_magic_admin.ajax_url,
        type: "POST",
        data: {
          action: "ai_magic_get_models",
          nonce: aiMagicSettings.settingsNonce,
          provider: provider,
          api_key: apiKey // Pass the API key explicitly
        },
        success: function (response) {
          if (response.success) {
            let html = "";
            if (response.data.length === 0) {
              html = '<div style="grid-column: 1 / -1; text-align: center; padding: 20px;">No models found. Check your API key.</div>';
            } else {
              response.data.forEach(function (model) {
                html += `
                  <label class="ai-magic-model-card">
                      <input 
                          type="radio" 
                          name="ai_magic_${provider}_model" 
                          value="${model.id}"
                          class="ai-magic-provider-model-input"
                          data-provider="${provider}"
                      >
                      <div class="ai-magic-model-badge" style="background: #6b7280;">${provider}</div>
                      <div class="ai-magic-model-info">
                          <h4>${model.name}</h4>
                          <p>${model.id}</p>
                          ${model.context_length ? `<div class="ai-magic-model-stats"><div class="stat"><span class="label">Context</span><span class="value">${model.context_length}</span></div></div>` : ''}
                      </div>
                      <div class="ai-magic-model-check">
                          <span class="dashicons dashicons-yes"></span>
                      </div>
                  </label>
                `;
              });
            }
            list.html(html);
          } else {
            list.html('<div style="grid-column: 1 / -1; color: red; text-align: center; padding: 20px;">Error: ' + (response.data || "Unknown error") + '</div>');
          }
        },
        error: function () {
          list.html('<div style="grid-column: 1 / -1; color: red; text-align: center; padding: 20px;">Connection error.</div>');
        },
        complete: function () {
          btn.html(originalText);
          btn.prop("disabled", false);
        },
      });
    });
  });
})(jQuery);
