<script setup>
import { ref, onMounted, watch } from 'vue'
import { useChatStore } from '../stores/chatstore'
import { generateResponse } from '../services/api'

const chatStore = useChatStore()
const isDrawerOpen = ref(true)
const isMiniVariant = ref(false)
const inputMessage = ref('')

const toggleDrawer = () => {
  isDrawerOpen.value = !isDrawerOpen.value
  isMiniVariant.value = !isMiniVariant.value
}

const selectChat = (index) => {
  chatStore.selectedChatIndex = index
}

const createNewChat = () => {
  chatStore.chatList.push({
    id: `chat${Date.now()}`,
    name: `Chat ${chatStore.chatList.length + 1}`,
    messages: []
  })
  chatStore.selectedChatIndex = chatStore.chatList.length - 1
  saveChatsToLocalStorage()
}

const saveChatName = (index, newName) => {
  if (newName.trim() !== '') {
    chatStore.updateChat(index, { name: newName.trim() })
    saveChatsToLocalStorage()
  }
}

const deleteChat = (index) => {
  chatStore.chatList.splice(index, 1)
  if (chatStore.chatList.length > 0) {
    chatStore.selectedChatIndex = Math.max(0, index - 1)
  } else {
    createNewChat()
  }
  saveChatsToLocalStorage()
}

const saveChatsToLocalStorage = () => {
  localStorage.setItem('chatHistory', JSON.stringify(chatStore.chatList))
}

const sendMessage = async () => {
  if (inputMessage.value.trim() !== '' && chatStore.selectedChatIndex !== null) {
    const userMessage = inputMessage.value.trim()
    const currentChat = chatStore.chatList[chatStore.selectedChatIndex]
    
    // Se for a primeira mensagem do chat e o nome for o padrão, atualiza o nome
    if (currentChat.messages.length === 0 && currentChat.name.startsWith('Chat ')) {
      currentChat.name = userMessage
    }
    
    chatStore.addMessage(chatStore.selectedChatIndex, {
      text: userMessage,
      isUser: true,
      timestamp: new Date().toISOString()
    })
    
    inputMessage.value = ''
    saveChatsToLocalStorage()

    try {
      chatStore.addMessage(chatStore.selectedChatIndex, {
        text: '...',
        isUser: false,
        isLoading: true
      })

      const botResponse = await generateResponse(userMessage)
      
      const messages = chatStore.chatList[chatStore.selectedChatIndex].messages
      const loadingIndex = messages.findIndex(m => m.isLoading)
      if (loadingIndex !== -1) {
        messages[loadingIndex] = {
          text: botResponse,
          isUser: false,
          timestamp: new Date().toISOString()
        }
      }
      
      saveChatsToLocalStorage()
    } catch (error) {
      console.error('Error sending message:', error)
    }
  }
}

onMounted(async () => {
  const userId = 'user123'
  await chatStore.loadChats(userId)
  if (chatStore.chatList.length === 0) {
    createNewChat()
  }
})

watch(() => chatStore.chatList, saveChatsToLocalStorage, { deep: true })
</script>

<template>
  <v-container fluid class="chat-layout pa-0">
    <!-- Drawer Lateral -->
    <v-navigation-drawer
      v-model="isDrawerOpen"
      :mini-variant="isMiniVariant"
      app
      permanent
      class="chat-drawer"
    >
      <v-list>
        <v-list-item v-if="!isMiniVariant">
          <v-row align="center" justify="space-between" style="width: 100%">
            <v-col cols="auto">
              <v-list-item-title class="text-h6">Chats</v-list-item-title>
            </v-col>
            <v-col cols="auto">
              <v-btn icon @click="createNewChat" color="primary">
                <v-icon>mdi-plus</v-icon>
              </v-btn>
            </v-col>
          </v-row>
        </v-list-item>

        <v-list-item
          v-for="(chat, index) in chatStore.chatList"
          :key="chat.id"
          @click="selectChat(index)"
          :class="{ 'chat-selected': chatStore.selectedChatIndex === index }"
          v-if="!isMiniVariant"
        >
          <template v-slot:prepend>
            <v-icon>mdi-chat</v-icon>
          </template>
          
          <v-list-item-content>
            <v-list-item-title>
              <v-text-field
                v-model="chat.name"
                @blur="saveChatName(index, chat.name)"
                hide-details
                dense
                variant="plain"
                @keyup.enter="$event.target.blur()"
              />
            </v-list-item-title>
          </v-list-item-content>

          <template v-slot:append>
            <v-btn icon small @click.stop="deleteChat(index)">
              <v-icon>mdi-delete</v-icon>
            </v-btn>
          </template>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>

    <!-- Área principal do chat -->
    <v-main class="chat-main">
      <!-- Mensagens -->
      <div class="messages-container">
        <v-list class="messages-list">
          <v-list-item
            v-for="(message, index) in chatStore.chatList[chatStore.selectedChatIndex]?.messages"
            :key="index"
            class="message-item"
          >
            <v-row :justify="message.isUser ? 'end' : 'start'" no-gutters>
              <v-col cols="auto" :class="message.isUser ? 'mr-2' : 'ml-2'" style="max-width: 80%;">
                <v-card
                  :class="[
                    'message-card',
                    message.isUser ? 'user-message' : 'received-message'
                  ]"
                  elevation="0"
                >
                  <v-card-text>{{ message.text }}</v-card-text>
                </v-card>
              </v-col>
            </v-row>
          </v-list-item>
        </v-list>
      </div>

      <!-- Área de input -->
      <div class="input-container">
        <v-textarea
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="Digite sua mensagem..."
          rows="1"
          auto-grow
          hide-details
          class="message-input"
          background-color="white"
        >
          <template v-slot:append>
            <v-btn icon @click="sendMessage" class="send-button" color="primary">
              <v-icon>mdi-send</v-icon>
            </v-btn>
          </template>
        </v-textarea>
      </div>
    </v-main>
  </v-container>
</template>

<style scoped>
.chat-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.chat-drawer {
  width: 280px;
  border-right: 1px solid #e0e0e0;
}

.chat-main {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f8f9fa;
}

.messages-list {
  background: transparent;
  padding-bottom: 60px;
}

.message-item {
  padding: 4px 16px;
  margin-bottom: 8px;
}

.message-card {
  max-width: 100%;
  border-radius: 16px;
  margin: 4px 0;
  padding: 8px;
}

.user-message {
  background-color: #e3f2fd !important;
  border-bottom-right-radius: 4px;
}

.received-message {
  background-color: white !important;
  border-bottom-left-radius: 4px;
}

.input-container {
  padding: 16px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  position: absolute;
  bottom: 0;
  left: 280px;
  right: 0;
}

.message-input {
  border-radius: 12px;
  background-color: #f8f9fa !important;
  padding: 8px;
}

.send-button {
  margin: 8px;
}

.chat-selected {
  background-color: #f0f4f8;
}
</style>
