<template>
  <v-container fluid>
    <v-row justify="space-between">
      <!-- Card de Treinamento -->
      <v-col cols="12" md="6">
        <v-card class="mx-auto card" width="100%">
          <v-toolbar class="header">
            <v-toolbar-title class="text">Train Lucy</v-toolbar-title>
          </v-toolbar>
          <v-tabs v-model="tab" color="primary" grow>
            <v-tab value="1"><v-icon>mdi-file-pdf-box</v-icon></v-tab>
            <v-tab value="2"><v-icon>mdi-text-box</v-icon></v-tab>
            <v-tab value="3"><v-icon>mdi-web</v-icon></v-tab>
          </v-tabs>

          <v-window v-model="tab">
            <!-- Aba 1: PDF ou Imagens -->
            <v-window-item value="1">
              <v-card-text>
                <div 
                  class="upload-box"
                  @dragover.prevent="onDragOver"
                  @dragleave.prevent="onDragLeave"
                  @drop.prevent="onDrop($event, ['pdf', 'png', 'jpg', 'jpeg'])"
                  :class="{ 'dragging': isDragging }">
                  <v-icon size="x-large" color="primary">mdi-cloud-upload</v-icon>
                  <p>Arraste arquivos PDF ou imagens</p>
                </div>
                <v-file-input
                  v-model="files"
                  accept=".pdf,.png,.jpg,.jpeg"
                  label="Enviar PDF ou Imagens"
                  multiple
                  variant="outlined"
                  @update:model-value="handleFileUpload($event, ['pdf', 'png', 'jpg', 'jpeg'])"
                ></v-file-input>
              </v-card-text>
            </v-window-item>

            <!-- Aba 2: Arquivos de Texto -->
            <v-window-item value="2">
              <v-card-text>
                <div 
                  class="upload-box"
                  @dragover.prevent="onDragOver"
                  @dragleave.prevent="onDragLeave"
                  @drop.prevent="onDrop($event, ['txt'])"
                  :class="{ 'dragging': isDragging }">
                  <v-icon size="x-large" color="primary">mdi-cloud-upload</v-icon>
                  <p>Arraste arquivos de Texto ou clique para enviar</p>
                </div>
                <v-file-input
                  v-model="files"
                  accept=".txt"
                  label="Enviar Arquivos de Texto"
                  multiple
                  variant="outlined"
                  @update:model-value="handleFileUpload($event, ['txt'])"
                ></v-file-input>
              </v-card-text>
            </v-window-item>

            <!-- Aba 3: URLs -->
            <v-window-item value="3">
              <v-card-text>
                <v-btn 
                  color="primary" 
                  block 
                  @click="showUrlDialog = true"
                >
                  Adicionar URL
                </v-btn>
                <v-dialog v-model="showUrlDialog" max-width="500">
                  <v-card>
                    <v-card-title>Digite a URL</v-card-title>
                    <v-card-text>
                      <v-text-field
                        v-model="url"
                        label="URL"
                        placeholder="https://exemplo.com/arquivo"
                        variant="outlined"
                        density="compact"
                      ></v-text-field>
                    </v-card-text>
                    <v-card-actions>
                      <v-spacer></v-spacer>
                      <v-btn color="primary" @click="handleUrlUpload">Enviar</v-btn>
                      <v-btn color="secondary" @click="showUrlDialog = false">Cancelar</v-btn>
                    </v-card-actions>
                  </v-card>
                </v-dialog>
              </v-card-text>
            </v-window-item>
          </v-window>

          <!-- Lista de arquivos -->
          <v-divider v-if="uploadedFiles.length > 0"></v-divider>
          <v-list v-if="uploadedFiles.length > 0">
            <v-list-subheader>Arquivos carregados</v-list-subheader>
            <v-list-item
              v-for="(file, index) in uploadedFiles"
              :key="index"
              :title="file.name"
              :subtitle="formatFileSize(file.size)"
            >
              <template v-slot:append>
                <v-btn
                  icon="mdi-delete"
                  color="error"
                  variant="text"
                  @click="removeFile(index)"
                ></v-btn>
              </template>
            </v-list-item>
          </v-list>

          <!-- Botão de Treinar -->
          <v-divider v-if="uploadedFiles.length > 0"></v-divider>
          <v-btn 
            color="#4cc9f0" 
            block
            @click="trainModel"
            :disabled="uploadedFiles.length === 0"
          >
            Treinar Lucy
          </v-btn>
        </v-card>
      </v-col>

      <!-- Card de Interação com Lucy -->
      <v-col cols="12" md="6">
        <v-card class="mx-auto card" width="100%">
          <v-toolbar class="header">
            <v-toolbar-title class="text">Converse com Lucy</v-toolbar-title>
          </v-toolbar>

          <v-card-text v-if="!modelTrained && !isTraining">
            <p>Treine Lucy antes de iniciar a conversa.</p>
          </v-card-text>
          <v-card-text v-else-if="isTraining">
            <p>Lucy está sendo treinada... Aguarde!</p>
          </v-card-text>
          <v-card-text v-else>
            <v-list>
              <v-list-subheader>Conversa com Lucy</v-list-subheader>
              <v-list-item v-for="(message, index) in chatHistory" :key="index">
                <v-list-item-content>
                  <v-list-item-title :class="{ 'user-message': message.sender === 'user' }">
                    {{ message.sender }}: {{ message.text }}
                  </v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list>
            <v-text-field
              v-model="userMessage"
              label="Digite sua mensagem"
              placeholder="Pergunte algo à Lucy"
              variant="outlined"
              density="compact"
              @keyup.enter="sendMessage"
              :disabled="!modelTrained"
            ></v-text-field>
            <v-btn 
              color="primary" 
              block 
              @click="sendMessage" 
              :disabled="!modelTrained"
            >
              Enviar
            </v-btn>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup>
import { ref } from 'vue'

const tab = ref('1')
const files = ref([])
const uploadedFiles = ref([])
const isDragging = ref(false)
const showUrlDialog = ref(false)
const url = ref('')
const modelTrained = ref(false)
const isTraining = ref(false) // Estado para verificar se Lucy está sendo treinada
const chatHistory = ref([])
const userMessage = ref('')

const formatFileSize = (size) => {
  if (size === 'N/A') return size
  const units = ['B', 'KB', 'MB', 'GB']
  let formattedSize = size
  let unitIndex = 0
  
  while (formattedSize >= 1024 && unitIndex < units.length - 1) {
    formattedSize /= 1024
    unitIndex++
  }
  
  return `${Math.round(formattedSize * 100) / 100} ${units[unitIndex]}`
}

const handleFileUpload = (newFiles, allowedExtensions) => {
  if (!newFiles) return
  
  const validFiles = Array.from(newFiles).filter(file => {
    const ext = file.name.split('.').pop().toLowerCase()
    return allowedExtensions.includes(ext)
  })
  
  uploadedFiles.value.push(...validFiles)
  files.value = []
}

const handleUrlUpload = () => {
  if (url.value.trim()) {
    uploadedFiles.value.push({
      name: url.value,
      type: 'url',
      size: 'N/A'
    })
    url.value = ''
    showUrlDialog.value = false
  }
}

const removeFile = (index) => {
  uploadedFiles.value.splice(index, 1)
}

const onDrop = (event, allowedExtensions) => {
  isDragging.value = false
  const droppedFiles = event.dataTransfer.files
  
  if (droppedFiles.length) {
    handleFileUpload(droppedFiles, allowedExtensions)
  }
}

const onDragOver = () => isDragging.value = true
const onDragLeave = () => isDragging.value = false

const trainModel = () => {
  isTraining.value = true
  setTimeout(() => {
    modelTrained.value = true
    isTraining.value = false
    console.log('Lucy foi treinada com os arquivos:', uploadedFiles.value)
  }, 3000) // Simula o tempo de treinamento
}

const sendMessage = () => {
  if (userMessage.value.trim()) {
    chatHistory.value.push({ sender: 'user', text: userMessage.value })
    chatHistory.value.push({ sender: 'Lucy', text: `Você disse: "${userMessage.value}"` })
    userMessage.value = ''
  }
}
</script>

<style scoped>
.header {
  background: linear-gradient(145deg, #eeeded, #ffffff);
}

.card {
  color: #6c00b5;
  border-radius: 25px;
  background: linear-gradient(145deg, #eeeded, #ffffff);
  box-shadow:  20px 20px 60px #d9d9d9,
              -20px -20px 60px #ffffff;
}

.upload-box {
  margin: 20px 0;
  border: 2px dashed #ccc;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  transition: all 0.3s;
  cursor: pointer;
}

.upload-box.dragging {
  background-color: #e3f2fd;
  border-color: #64b5f6;
}

.upload-box p {
  margin-top: 8px;
  font-size: 14px;
  color: #777;
}

.user-message {
  font-weight: bold;
}

.text {
  color: #6c00b5;
}
</style>