jQuery(document).ready(function($) {
  const $form = $('#llm-config-form');
  const $connectBtn = $('#mindweco-connect-api');
  const $formInputs = jQuery('#llm-config-form .form-input');
  const $disconnectBtn = $('#mindweco-llm-disconnect-api');

  if ($form.length === 0) {
    return;
  }

  function setProviderFromActiveTab() {
    const $activeTab = $('.mindweco-nav-tab.nav-tab-active');
    const provider = $activeTab.data('provider');
    if (provider) $('#api-provider').val(provider);
  }

  $(document).on('click', '.mindweco-nav-tab', function(e) {
    e.preventDefault();
    $('.mindweco-nav-tab').removeClass('nav-tab-active');
    $(this).addClass('nav-tab-active');
    const tab = $(this).data('tab');
    $('.tab-content').hide();
    $('#tab-' + tab).show();
    setProviderFromActiveTab();
  });

  $(document).on('click', '.go-to-tab-btn', function(e) {
    e.preventDefault();
    const tab = $(this).data('tab');
    $('.mindweco-nav-tab').removeClass('nav-tab-active');
    $('.mindweco-nav-tab[data-tab="' + tab + '"]').addClass('nav-tab-active');
    $('.tab-content').hide();
    $('#tab-' + tab).show();
    setProviderFromActiveTab();
  });

  setProviderFromActiveTab();
  const isConnected = mindwecoLLMConfig.llm_config_id;
  if (isConnected) {
    $formInputs.not('#api-key').prop('disabled', true);
    $connectBtn.hide();
    $disconnectBtn.removeClass('d-none').show();
    $('.btn-save-changes').addClass('d-none');
    $('.btn-update-llm').show();
  }

  $(document).on('click', '#toggle-api-key', function() {
    const apiKeyInput = document.getElementById('api-key');
    const $icon = $('#eye-icon');
    if (apiKeyInput.type === 'password') {
      apiKeyInput.type = 'text';
      $icon.removeClass('bi-eye').addClass('bi-eye-slash');
    } else {
      apiKeyInput.type = 'password';
      $icon.removeClass('bi-eye-slash').addClass('bi-eye');
    }
  });

  $form.on('submit', function(e) {
    e.preventDefault();
    if ($connectBtn.prop('disabled')) return;
    const originalBtnText = $connectBtn.html();
    $connectBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> Connecting...');
    const formData = {
      action: 'mindweco_create_attach_llm_config_to_indexing',
      nonce: mindwecoLLMConfig.nonce,
      name: $('#api-llm-name').val(),
      llm_base_url: $('#api-base-url-llm').val(),
      model_name: $('#api-model-name').val(),
      provider: $('#api-provider').val(),
      api_key: $('#api-key').val()
    };
    const emptyFields = [];
    for (const key in formData) {
      if (!formData[key]) emptyFields.push(key);
    }
    if (emptyFields.length) {
      MindwecoToast.error('Required fields missing: ' + emptyFields.join(', '));
      $connectBtn.prop('disabled', false).html(originalBtnText);
      return;
    }
    $.ajax({
      url: mindwecoLLMConfig.ajax_url,
      type: 'POST',
      data: formData,
      success: function(response) {
        if (response.success) {
          MindwecoToast.success(response.data.message || 'LLM Configuration saved successfully!');
          $connectBtn.hide();
          $formInputs.not('#api-key').prop('disabled', true);
          $disconnectBtn.removeClass('d-none').show();
          $('.btn-save-changes').addClass('d-none');
          $('.btn-update-llm').show();
        } else {
          MindwecoToast.error(response.data?.message || 'Failed to save LLM configuration');
          $connectBtn.prop('disabled', false).html(originalBtnText);
        }
      },
      error: function(xhr, status, error) {
        MindwecoToast.error('An error occurred: ' + error + ' (HTTP ' + xhr.status + ')');
        $connectBtn.prop('disabled', false).html(originalBtnText);
      }
    });
  });

  $(document).on('click', '.btn-update-llm', function() {
    $('.btn-save-changes').removeClass('d-none');
    $('.btn-update-llm').hide();
    $('#llm-config-form').find('input, select, textarea').prop('disabled', false).addClass('update-input-on-edit');
  });

  $(document).off('click', '#llm-save-changes').on('click', '#llm-save-changes', function(e) {
    e.preventDefault();
    const $btn = $(this);
    $btn.prop('disabled', true).text('Saving...');
    const data = {
      action: 'mindweco_update_llm_config',
      nonce: mindwecoLLMConfig.nonce,
      name: $('#api-llm-name').val(),
      llm_base_url: $('#api-base-url-llm').val(),
      model_name: $('#api-model-name').val(),
      provider: $('#api-provider').val(),
      api_key: $('#api-key').val()
    };
    $.post(mindwecoLLMConfig.ajax_url, data).done(function(response) {
      if (!response || typeof response !== 'object') {
        MindwecoToast.error('Unexpected server response.');
        return;
      }
      const message = response?.data?.message || 'LLM updated successfully!';
      if (response.success) {
        MindwecoToast.success(message);
        $('#llm-config-form').find('input, select, textarea').not('#api-key').prop('disabled', true);
        $('.btn-save-changes').addClass('d-none');
        $('.btn-update-llm').show();
      } else {
        MindwecoToast.error(message);
      }
    }).fail(function() {
      MindwecoToast.error('AJAX request failed');
    }).always(function() {
      $btn.prop('disabled', false).text('Save Changes');
    });
  });

  $(document).off('click', '#mindweco-llm-disconnect-api').on('click', '#mindweco-llm-disconnect-api', function(e) {
    e.preventDefault();
    MindwecoModal.confirm('Confirm Disconnect', 'Are you sure you want to disconnect this configuration?', function() {
      const $button = $('#mindweco-llm-disconnect-api');
      const originalHtml = $button.html();
      $button.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> Disconnecting...');
      $.post(mindwecoLLMConfig.ajax_url, {
        action: 'mindweco_delete_llm_config_ajax',
        nonce: mindwecoLLMConfig.nonce
      }).done(function(response) {
        if (response.success) {
          MindwecoToast.success(response.data.message);
          setTimeout(() => location.reload(), 1000);
        } else {
          MindwecoToast.error(response.data.message);
          $button.prop('disabled', false).html(originalHtml);
        }
      }).fail(function() {
        MindwecoToast.error('AJAX request failed');
        $button.prop('disabled', false).html(originalHtml);
      });
    }, 'Disconnect LLM', 'btn-danger');
  });
});