// chat functionality
const hamburgerMenu = document.querySelector('.hamburger-menu');
const sidepanel = document.querySelector('#sidepanel');
const contactsList = document.querySelector('#contacts ul');
const addContact = document.querySelector('#backToDashboard');
const settings = document.querySelector('#settings');
// const base_url = "http://127.0.0.1:8000";
const base_url = "https://start.brainpod.ai";
console.log(token);


hamburgerMenu.addEventListener('click', function() {
  this.classList.toggle('open');
  
  if (this.classList.contains('open')) {
    sidepanel.style.transform = 'translateX(0%)';
    contactsList.style.display = 'block';
    addContact.style.display = 'block';
    settings.style.display = 'block';
  } else {
    sidepanel.style.transform = 'translateX(-80%)';
    contactsList.style.display = 'none';
    addContact.style.display = 'none';
    settings.style.display = 'none';
  }
});

$(document).ready(function() {
    var url_user = base_url + "/api/chat/user";
    var url_chat = base_url + "/api/chat/chat";
    console.log(token);

      $.ajax({
        url: url_user,
        type: "GET",
        beforeSend: function(xhr) {
          xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function(response) {
          // Update the HTML elements with the received data
          chrome.storage.local.set({ imageUrl: response.image_url }).then(() => {
  
          });
          $("#profile-img").attr("src", response.image_url);
          $("#profile .wrap p").text(response.name);
        },
        error: function(xhr, status, error) {
          console.log(error);
        }
      });
  
      $.ajax({
          url: url_chat,
          type: "GET",
          beforeSend: function(xhr){
              xhr.setRequestHeader("Authorization", "Bearer " + token);
          },
          success: function(response) {
              var chats = response.chats;
              $.each(chats, function(index, chat){
                  var chat_list = '<li class="contact" data-chatid='+chat.id+'>'+
                  '<div class="wrap">'+
                  '<div class="meta">'+
                  '<p class="name"> '+chat.title+'</p>'+
                  '</div>'+
                  '</div>'+
                  '</li>';
  
                  $('#contacts ul').append(chat_list);
              });
          },
          error: function(xhr, status, error) {
              console.log(error);
          }
      });
});

$(document).on('click', '.contact', function() {
    // Remove active class from any other active elements
    $('.contact.active').removeClass('active');
    hamburgerMenu.click();

    // Add active class to the clicked element
    $(this).addClass('active');

    // Get the chatId from the data attribute
    var chatId = $(this).data('chatid');

    // Call the changeChatWindow function
    changeChatWindow(chatId);
});

function changeChatWindow(chatId)
{
    $('#chat-history').html('');
    $('#loading').removeAttr('hidden');
    $('#emptyChat').attr('hidden', 'hidden');
    var history_url = base_url + "/api/chat/history/" + chatId;

    $.ajax({
        url: history_url,
        type: 'GET',
        beforeSend: function(xhr){
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function(response) {
            console.log(response);
            var chatHistory = response.chat_history;

            if (chatHistory.length < 1)
            {
                $('#emptyChat').removeAttr('hidden');
                return;
            }

            // Loop through each chat and create elements
            $.each(chatHistory, function(index, chat) {
                chrome.storage.local.get(["imageUrl"]).then((result) => {
                    var imageUrl = result.imageUrl;
                    var chatElement = '<li class="sent">' +
                    '<img src="'+imageUrl+'" alt="" />' +
                    '<p>' + chat.chat + '</p>' +
                    '</li>' +
                    '<li class="replies">' +
                    '<img src="assets/images/Blue_purple_colorful_smart_brain_logo.png" alt="" />' +
                    '<p>' + chat.reply + '</p>' +
                    '</li>';

                    $('#chat-history').append(chatElement);
                });
                
                $('#emptyChat').attr('hidden', 'hidden');
            });
        },
        error: function(xhr, status, error) {
            // Handle any error that occurred during the AJAX request
            console.log(error);
        },
        complete: function() {
            // This will run regardless of success or error
            $('#loading').attr('hidden', 'hidden');
        }
    });
}

function newMessage() {
  message = $(".message-input input").val();

  // generate chat response
  chatId = $('.contact.active').data('chatid');

  console.log(chatId);
  $.ajax({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    type: 'POST',
    url: base_url + '/api/chat/send',
    timeout: 120000,
    data: {
      message: message,
      chat_id: chatId
    },
    beforeSend: function(xhr){
    xhr.setRequestHeader("Authorization", "Bearer " + token);
    
	if($.trim(message) == '') {
		return false;
	}

    chrome.storage.local.get(["imageUrl"]).then((result) => {
        var imageUrl = result.imageUrl;
        $('<li class="sent"><img src="'+imageUrl+'" alt="" /><p>' + message + '</p></li>').appendTo($('#chat-history'));
    });

    setTimeout(() => {
        $('.message-input input').val(null);
        var chatElement = '<li class="replies active-chat">' +
                            '<img src="assets/images/Blue_purple_colorful_smart_brain_logo.png" alt="" />' +
                            '<p>'+
                            '<span class="loading">'+
                            'Typing'+
                            '<span class="loading__dot"></span>'+
                            '<span class="loading__dot"></span>'+
                            '<span class="loading__dot"></span>'+
                            '</span>'+
                            '</p>'+
                          '</li>';
        $('#chat-history').append(chatElement);
        var messagesDiv = document.querySelector(".messages");
      var chatHistory = document.getElementById("chat-history");
      var repliesList = chatHistory.getElementsByClassName("replies");

      if (repliesList.length > 0) {
        var lastReply = repliesList[repliesList.length - 1];
        var lastReplyParagraph = lastReply.querySelector("p");
        messagesDiv.scrollTop = lastReplyParagraph.offsetTop;
      }
      }, 500);
      
	
      $("#message-input").prop("disabled", true);
    },
    success: function(response) {
      if (response.new_chat == 1){
        $('.contact').removeClass('active');
        // Create the new list item
        var listItem = `
          <li class="contact active" data-chatid="`+response.parent_id+`">
            <div class="wrap">
              <div class="meta">
                <p class="name"><i class="fa-sharp fa-regular fa-message"></i> `+response.title+`</p>
              </div>
            </div>
          </li>
        `;

        // Add the new list item as the second child of #contacts ul
        var $ul = $('#contacts ul');
        var $newChat = $ul.find('li:eq(0)');
        $newChat.after(listItem);
        // $('input[name="credit"]').val(response.new_tokens);
      }

      $('.replies.active-chat p').html(response.message);
      $(".message-input input").prop("disabled", false);
      $('.replies').removeClass('active-chat');
      var messagesDiv = document.querySelector(".messages");
      var chatHistory = document.getElementById("chat-history");
      var repliesList = chatHistory.getElementsByClassName("replies");

      if (repliesList.length > 0) {
        var lastReply = repliesList[repliesList.length - 1];
        var lastReplyParagraph = lastReply.querySelector("p");
        messagesDiv.scrollTop = lastReplyParagraph.offsetTop;
      }
      console.log(response);
    },
    error: function(response) {
      if(response.responseJSON.error == "insufficient_token_credit"){
          var message = 'Oops, ' + response.responseJSON.message;
          var confirmAddCredits = confirm(message);

          if (confirmAddCredits) {
            window.location.href = '/setting/credits';
          }
      }
    }
  });
}

$('.submit').click(function() {
    newMessage();
    $('#emptyChat').attr('hidden', 'hidden');
});

$(window).on('keydown', function(e) {
    if (e.which == 13) {
        newMessage();
        $('#emptyChat').attr('hidden', 'hidden');
        return false;
    }
  });

  var back = document.getElementById('backToDashboard');
  back.addEventListener('click', function(event) {
    event.preventDefault();
    window.location.href = 'dashboard.html';
  });