<script setup>
import axios from "axios";
import {v4 as uuidv4} from "uuid";
import { ref, onMounted, nextTick, watch } from "vue";
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const messages = ref([]);
const userMessage = ref("");
const loading = ref(false);
const userChats = ref([]);
const activeChatId = ref(route.params.chatId || null);

const API_BASE_URL = import.meta.env.MODE === "production" 
  ? import.meta.env.VITE_URL_PRODUCTION
  : import.meta.env.VITE_URL_LOCAL;

const sessionId = ref(localStorage.getItem("session_id") || uuidv4());
localStorage.setItem("session_id", sessionId.value);

const chatMessagesRef = ref(null);

onMounted(async () => {
  await fetchUserChats();
});

const fetchUserChats = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/chats/me`, {
      headers: { "X-Session-Id": sessionId.value },
    });
    userChats.value = response.data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  } catch (error) {
    console.error("Error fetching chats", error);
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
    }
  });
};

const loadChat = async (chatId) => {
  try {
    messages.value = []
    const response = await axios.get(
      `${API_BASE_URL}/chats/${chatId}`,
      { headers: { "X-Session-Id": sessionId.value } }
    );
    
    if (response.data.messages) {
      response.data.messages.forEach(msg => {
        messages.value.push({ text: msg.user, sender: "user" });
        messages.value.push({ text: msg.bot, sender: "bot" });
      });
    }
    scrollToBottom();
  } catch (error) {
    messages.value.push({ text: "Error al carregar el xat", sender: "bot" });
    scrollToBottom();
  }
};

watch(
  () => route.params.chatId,
  (newChatId) => {
    if (newChatId) {
      activeChatId.value = newChatId
      loadChat(newChatId)
    }
  },
  { immediate: true }
)

const sendMessage = async () => {
  if (!userMessage.value.trim()) return;

  messages.value.push({ text: userMessage.value, sender: "user" });
  const userInput = userMessage.value;
  userMessage.value = "";
  loading.value = true;

  try {
    const response = await axios.post(
      `${API_BASE_URL}/chats/rag/`,
      { 
        message: userInput,
        chat_id: activeChatId.value
      },
      { headers: { "X-Session-Id": sessionId.value } }
    );
    
    messages.value.push({ text: response.data.response, sender: "bot" });
    
    if (!activeChatId.value && response.data.chat_id) {
      activeChatId.value = response.data.chat_id;
      await fetchUserChats();
    } else if(activeChatId.value == response.data.chat_id) {
      await fetchUserChats();
    }
    scrollToBottom();
  } catch (error) {
    messages.value.push({ text: "Error en la resposta", sender: "bot" });
    scrollToBottom();
  } finally {
    loading.value = false;
  }
};

const selectChat = (chatId) => {
  if (activeChatId.value !== chatId) {
    router.push(`/${chatId}`)
  }
}
</script>

<template>
  <div class="chat-app-container">
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h3>OTPSD UB</h3>
        <button @click="activeChatId = null; messages = []" class="new-chat-btn">
          <i class="fas fa-plus"></i> Nou xat
        </button>
      </div>
      <div class="chat-history">
        <div 
          v-for="chat in userChats" 
          :key="chat._id"
          @click="selectChat(chat._id)"
          class="chat-item"
          :class="{ 'active': chat._id === activeChatId }"
        >
          <div class="chat-preview">
            <div class="chat-title">Xat #{{ chat._id.slice(-4)}}</div>
            <div v-if="chat.messages" class="last-message">
              {{ chat.messages[0]?.user || 'Nuevo chat' }}
            </div>
          </div>
        </div>
      </div>
      <div class="sidebar-footer">
        <img src="../assets/logo.jpg" alt="Logo RIMDA" class="sidebar-logo" />
        <img src="../assets/ub.jpg" alt="Logo UB" class="sidebar-logo-ub" />
      </div>
    </div>

    <div class="chat-main">
      <div class="chat-header" v-if="activeChatId">
        <div class="chat-title">Xat #{{ activeChatId}}</div>
      </div>
      
      <div class="chat-messages" ref="chatMessagesRef">
        <div v-if="messages.length === 0" class="welcome-screen">
          <div class="welcome-banner">
            <h5>Benvingut al xatbot de la OTPSD!</h5>
              <p class="mb-2">Aquest és un xat interactiu on pots:</p>
              <ul class="text-start">
                <li>Fer preguntes sobre les bases de les convocatòries dels diferents tipus de projectes</li>
                <li>Preguntar sobre els grups d'innovació docent</li>
                <li>Resoldre els teus dubtes sobre com millorar com a docent</li>
              </ul>
              <p class="mt-3">Per tal que el xat funcioni correctament, és important especificar el context sobre el que preguntes.</p>
              <p class="mt-3">Escriu el teu primer missatge per començar!</p>
          </div>
        </div>
        
        <div v-else class="messages-container">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            class="message"
            :class="msg.sender"
          >
            <div class="message-content">
              <div class="message-text">{{ msg.text }}</div>
            </div>
          </div>
          
          <div v-if="loading" class="loading-indicator">
            <div class="typing-animation">
              <div class="dot"></div>
              <div class="dot"></div>
              <div class="dot"></div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="message-input-container">
        <div class="input-wrapper">
          <input
            v-model="userMessage"
            @keyup.enter="sendMessage"
            placeholder="Escriu el teu missatge..."
            class="message-input"
          />
          <button @click="sendMessage" class="send-button" :disabled="!userMessage.trim()">
            <i class="fas fa-paper-plane"></i>
          </button>
        </div>
        <div class="input-footer">
          <small>OTTSD Chat Assistant pot cometre errors. En cas de dubtes consulta a l'oficina.</small>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-app-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.chat-sidebar {
  width: 280px;
  background-color: #ffffff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h3 {
  color: #4a6fa5;
  margin-bottom: 15px;
  font-weight: 600;
}

.new-chat-btn {
  width: 100%;
  padding: 10px;
  background-color: #4a6fa5;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.new-chat-btn:hover {
  background-color: #6b8cc6;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.chat-item {
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 5px;
  border: 1px solid #e0e0e0;
}

.chat-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.chat-item.active {
  background-color: #e3f2fd;
}

.chat-title {
  font-weight: 500;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.last-message {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: white;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.messages-container {
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.bot {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message.user .message-text {
  background-color: #e3f2fd;
  border-bottom-right-radius: 0;
  color: #333;
}

.message.bot .message-text {
  background-color: #4a5568;
  color: white;
  border-bottom-left-radius: 0;
}

.loading-indicator {
  display: flex;
  justify-content: flex-start;
  padding: 15px;
  color: #0000;
}

.typing-animation {
  display: flex;
  align-items: center;
  gap: 5px;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: rgb(0, 0, 0);
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

@keyframes bounce {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-5px); }
}

.message-input-container {
  padding: 15px 20px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
}

.input-wrapper {
  display: flex;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  background-color: white;
}

.message-input {
  flex: 1;
  padding: 12px 15px;
  border: none;
  outline: none;
  font-size: 14px;
  background-color: rgb(27, 27, 27);
  color: white;

}

.message-input::placeholder {
  color: #ffffff;
}

.send-button {
  padding: 0 15px;
  background-color: #4a6fa5;
  color: white;
  border: none;
  cursor: pointer;
}

.send-button:hover {
  background-color: #6b8cc6;
}

.send-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.input-footer {
  text-align: center;
  margin-top: 8px;
  color: #666;
  font-size: 12px;
}

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.welcome-screen {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.welcome-banner {
  background: #2563eb;
  color: #fff;
  border-radius: 16px;
  padding: 32px 24px;
  text-align: center;
  width: 100%;
  max-width: 420px;
  margin: 0 auto;
  box-shadow: 0 2px 12px #0002;
}



.welcome-banner h2 {
  color: #fff;
  margin-bottom: 12px;
}

.welcome-banner p {
  color: #e0e7ff;
  margin-bottom: 0;
}

.sidebar-footer {
  padding: 16px 0;
  text-align: center;
  border-top: 1px solid #e0e0e0;
  background: #fff;
}

.sidebar-logo {
  max-width: 120px;
  width: 100%;
  height: auto;
  opacity: 0.85;
}

.sidebar-logo-ub {
  max-width: 80px;
  width: 60%;
  height: auto;
  margin-top: 10px;
  opacity: 0.9;
}
</style>