var urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('apiKey');

// 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 = "https://start.brainpod.ai";
var user_img = "";
var ai_logo = "";




hamburgerMenu.addEventListener('click', function() {
	this.classList.toggle('open');

	if (this.classList.contains('open')) {
		sidepanel.style.transform = 'translateX(0%)';
		contactsList.style.display = 'block';
	} else {
		sidepanel.style.transform = 'translateX(-80%)';
		contactsList.style.display = 'none';
	}
});

jQuery(document).ready(function() {
	var url_user = base_url + "/api/chat/user";
	var url_chat = base_url + "/api/chat/chat";
	ai_logo = jQuery("#chat-image").attr('src');

	jQuery("#profile-img").attr("src", ai_logo);

	jQuery.ajax({
		url: url_user,
		type: "GET",
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Authorization", "Bearer " + token);
		},
		success: function(response) {
			user_img = response.image_url;
				jQuery("#profile-img").attr("src", user_img);
				jQuery("#profile .wrap p").text(response.name);
		},
		error: function(xhr, status, error) {
		}
	});

	jQuery.ajax({
		url: url_chat,
		type: "GET",
		beforeSend: function(xhr){
			xhr.setRequestHeader("Authorization", "Bearer " + token);
		},
		success: function(response) {
			var chats = response.chats;
			jQuery.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>';

				jQuery('#contacts ul').append(chat_list);
			});
		},
		error: function(xhr, status, error) {
		}
	});
});

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

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

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

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

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

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

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

			// Loop through each chat and create elements
			jQuery.each(chatHistory, function(index, chat) {
				var chatElement = '<li class="sent">' +
				'<img src="'+user_img+'" alt="" />' +
				'<p>' + chat.chat + '</p>' +
				'</li>' +
				'<li class="replies">' +
				'<img src="'+ai_logo+'" alt="" />' +
				'<p>' + chat.reply + '</p>' +
				'</li>';

				jQuery('#chat-history').append(chatElement);
			});

			jQuery('#emptyChat').attr('hidden', 'hidden');
		},
		error: function(xhr, status, error) {
			// Handle any error that occurred during the AJAX request
		},
		complete: function() {
			// This will run regardless of success or error
			jQuery('#loading').attr('hidden', 'hidden');
		}
	});
}

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

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

	jQuery.ajax({
		headers: {
			'X-CSRF-TOKEN': jQuery('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(jQuery.trim(message) == '') {
				return false;
			}

			jQuery('<li class="sent"><img src="'+user_img+'" alt="" /><p>' + message + '</p></li>').appendTo(jQuery('#chat-history'));
			setTimeout(() => {
				jQuery('.message-input input').val(null);
				var chatElement = '<li class="replies active-chat">' +
				'<img src="'+ai_logo+'" alt="" />' +
				'<p>'+
				'<span class="loading">'+
				'Typing'+
				'<span class="loading__dot"></span>'+
				'<span class="loading__dot"></span>'+
				'<span class="loading__dot"></span>'+
				'</span>'+
				'</p>'+
				'</li>';
				jQuery('#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);

			jQuery("#message-input").prop("disabled", true);
		},
		success: function(response) {
			if (response.new_chat == 1){
				jQuery('.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 jQueryul = jQuery('#contacts ul');
				var jQuerynewChat = jQueryul.find('li:eq(0)');
				jQuerynewChat.after(listItem);
				// jQuery('input[name="credit"]').val(response.new_tokens);
			}

			jQuery('.replies.active-chat p').html(response.message);
			jQuery(".message-input input").prop("disabled", false);
			jQuery('.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;
			}
		},
		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';
				}
			}
		}
	});
}

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

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