<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
const router = useRouter()

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

const isLoggedIn = ref(false)
const showLoginModal = ref(false)
const username = ref('')
const password = ref('')
const expandedIndex = ref(null)
const token = ref(localStorage.getItem("token"));

const rankingData = ref([])
const showSearchModal = ref(false)
const allChats = ref([])
const searchId = ref("");

function getToken() {
  return localStorage.getItem('token') || null
}

onMounted(() => {
  if (getToken()) {
    isLoggedIn.value = true
    showLoginModal.value = false
    fetchRanking()
  } else {
    isLoggedIn.value = false
    showLoginModal.value = true
  }
})

async function login() {
  try {
    const formData = new URLSearchParams()
    formData.append('username', username.value)
    formData.append('password', password.value)

    const response = await axios.post(
      `${API_BASE_URL}/login`,
      formData,
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      }
    )

    token.value = response.data.access_token
    localStorage.setItem('token', token.value)
    isLoggedIn.value = true
    showLoginModal.value = false
    showToast("successToast");
    await fetchRanking()
  } catch (error) {
    console.error('Login failed', error)
    showToast("errorToast");
  }
}

function logout() {
  localStorage.removeItem('token')
  isLoggedIn.value = false
  showLoginModal.value = true
  expandedIndex.value = null
  showToast("logoutToast");
}

function cancelLogin() {
  router.push('/')
}

function toggleExpand(index) {
  expandedIndex.value = expandedIndex.value === index ? null : index
}

async function fetchRanking() {
  try {
    const response = await axios.get(`${API_BASE_URL}/ranking`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    rankingData.value = response.data.ranking.map(item => ({
      title: `${item.views} vistes`,
      user_messages: item.messages
    }))
  } catch (error) {
    rankingData.value = []
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token')
      isLoggedIn.value = false
      showLoginModal.value = true
    }
    console.error('Error carregant el ranking', error)
  }
}

async function fetchAllChats() {
  try {
    const response = await axios.get(`${API_BASE_URL}/chats/all`, {
      headers: { Authorization: `Bearer ${getToken()}` }
    })
    allChats.value = response.data
  } catch (error) {
    allChats.value = []
    showToast("errorToast")
  }
}

function openSearchModal() {
  showSearchModal.value = true
  fetchAllChats()
}

function closeSearchModal() {
  showSearchModal.value = false
}

function goToChat(chatId) {
  router.push(`/${chatId}`)
  closeSearchModal()
}

const showToast = (id) => {
  let toastElement = document.getElementById(id);
  let toast = new bootstrap.Toast(toastElement);
  toast.show();
};

const filteredChats = computed(() =>
  allChats.value.filter(chat =>
    chat._id.toLowerCase().includes(searchId.value.trim().toLowerCase())
  )
)
</script>

<template>
  <div class="ranking-page">
    <div class="ranking-header d-flex justify-content-between align-items-center">
      <h2 class="mb-0 text-start">Ranking de consultes</h2>
      <div class="d-flex align-items-center">
        <button class="btn btn-light me-2" @click="openSearchModal">
           Cercar xat
        </button>
        <button v-if="isLoggedIn" class="btn btn-danger ms-1" @click="logout">
          Tancar sessió
        </button>
      </div>
    </div>

    <!-- Modal de login -->
    <div
      v-if="showLoginModal"
      class="modal fade show"
      tabindex="-1"
      role="dialog"
      style="display: block; background: rgba(0,0,0,0.5);"
    >
      <div class="modal-dialog modal-dialog-centered" style="max-width:400px; margin-top: 3rem;">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Iniciar Sessió</h5>
          </div>
          <div class="modal-body">
            <input
              type="text"
              v-model="username"
              class="form-control mb-2"
              placeholder="Usuari"
              autofocus
            />
            <input
              type="password"
              v-model="password"
              class="form-control mb-3"
              placeholder="Contrasenya"
              @keyup.enter="login"
            />
            <div class="d-flex gap-2">
              <button class="btn btn-success flex-grow-1" @click="login">Entrar</button>
              <button class="btn btn-secondary flex-grow-1" @click="cancelLogin">Cancel·lar</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="showSearchModal"
      class="modal fade show"
      tabindex="-1"
      role="dialog"
      style="display: block; background: rgba(0,0,0,0.5);"
    >
      <div class="modal-dialog modal-lg modal-dialog-centered" style="width:75vw; max-width:1200px;">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Tots els xats</h5>
            <button type="button" class="close" @click="closeSearchModal">
              <span>&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <input
              v-model="searchId"
              type="text"
              class="form-control mb-3"
              placeholder="Cerca per ID de xat"
              autofocus
            />
            <div v-if="filteredChats.length === 0" class="text-muted">No hi ha xats</div>
            <ul class="list-group" style="max-height: 350px; overflow-y: auto;">
              <li
                v-for="chat in filteredChats"
                :key="chat._id"
                class="list-group-item list-group-item-action"
                style="cursor:pointer"
                @click="goToChat(chat._id)"
              >
                Xat #{{ chat._id}} - {{ chat.email || 'Anònim' }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div v-if="isLoggedIn" class="container-fluid mt-5 pt-5">
      <div v-if="rankingData.length === 0" class="text-center text-muted mt-5 fs-4">
        No hi ha consultes
      </div>
      <div
        v-for="(item, index) in rankingData"
        :key="index"
        class="card custom-card"
      >
        <div
          class="card-header d-flex justify-content-between align-items-center"
          @click="toggleExpand(index)"
          style="cursor: pointer;"
        >
          <strong>{{ item.title }}</strong>
          <span>{{ expandedIndex === index ? '▲' : '▼' }}</span>
        </div>
        <div v-if="expandedIndex === index" class="card-body">
          <ul class="list-group list-group-flush">
            <li
              v-for="(msg, i) in item.user_messages"
              :key="i"
              class="list-group-item"
            >
              {{ msg.replace(/^user_message:/, '') }}
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div v-if="isLoggedIn" class="position-fixed top-0 end-0 p-3 z-3">
      <button class="btn btn-danger" @click="logout">
        Tancar sessió
      </button>
    </div>
  </div>
  <div id="successToast" class="toast position-fixed top-0 start-50 translate-middle-x mt-3 p-3 bg-success text-white border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body">✅ Login completat amb èxit!</div>
        <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>

    <div id="errorToast" class="toast position-fixed top-0 start-50 translate-middle-x mt-3 p-3 bg-danger text-white border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body">❌ Login Fallit!</div>
        <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>

    <div id="logoutToast" class="toast position-fixed top-0 start-50 translate-middle-x mt-3 p-3 bg-info text-white border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body">🚪 Sessió tancada amb èxit!</div>
        <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>

</template>



<style scoped>
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1050;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 2rem;
  overflow-y: auto;
}

/* Login modal */
.login-modal-panel {
  background: white;
  border-radius: 0.5rem;
  padding: 2rem 2.5rem;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
  margin: 4rem auto 0 auto;
  position: relative;
  top: 0;
  transform: none;
}

/* Search modal */
.search-modal-panel {
  background: white;
  border-radius: 0.5rem;
  padding: 2rem 2.5rem;
  width: 75vw;
  max-width: 1200px;
  min-width: 320px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
  margin: auto;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.card.custom-card {
  width: 80%;
  max-width: 80%;
  min-height: 160px;
  margin: 0 0 1rem 0;
  border-radius: 0;
  background-color: #e9ecef !important;
  box-shadow: 0 2px 8px #0001;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 1.5rem 1rem;
}

.card-body ul,
.card-body li {
  word-break: break-word;
  overflow-wrap: break-word;
}

.container-fluid {
  position: fixed;
  top: 20px;
  left: 0;
  width: 100vw;
  height: calc(100vh - 20px);
  overflow-y: auto;
  background: #fff;
  padding: 0 0 2rem 0;
}

#app{
    width: 100%;
}
.toast {
  z-index: 3060;
}

.ranking-header {
  width: 100vw;
  background: #2563eb;
  color: #fff;
  padding: 1.5rem 2rem 1rem 2rem;
  text-align: left;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1100;
  box-shadow: 0 2px 8px #0002;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100px; /* fixa l'alçada del header */
}

.ranking-header h2 {
  margin: 0;
  font-weight: 600;
  font-size: 2rem;
  letter-spacing: 1px;
}
</style>
