<template>
  <q-page padding>
    <div class="row items-center q-mb-md">
      <div class="text-h6 text-weight-bold">Évaluations clients</div>
      <q-chip v-if="lowCount" dense color="negative" text-color="white" class="q-ml-sm">{{ lowCount }} basse(s)<q-tooltip>Évaluations sous 5★</q-tooltip></q-chip>
      <q-space />
      <q-select v-model="sortKey" :options="sortOptions" dense outlined options-dense emit-value map-options class="q-mr-sm" style="min-width:215px">
        <template #prepend><q-icon name="sort" size="18px" /></template>
      </q-select>
      <q-btn flat round dense icon="refresh" color="grey-7" :loading="loading" @click="load"><q-tooltip>Rafraîchir</q-tooltip></q-btn>
    </div>

    <!-- Filtre dynamique (client) : recherche client/commentaire + chips note + presets. Le computed `sorted` réagit à filterState. -->
    <DynamicFilter v-model="filterState" search-placeholder="Client, commentaire…" :chip-groups="chipGroups"
      preset-key="filter.evaluations" :filtered-count="sorted.length" :total-count="ratings.length" class="q-mb-md" />

    <div v-if="loading && !ratings.length" class="flex flex-center q-pa-xl"><q-spinner size="36px" color="primary" /></div>
    <div v-else-if="!sorted.length" class="ops-card text-center text-grey-6 q-pa-xl" style="border-radius:12px">
      <q-icon name="reviews" size="40px" color="grey-4" class="q-mb-sm" /><br>
      Aucune évaluation pour le moment.
    </div>

    <q-list v-else bordered separator class="ops-card" style="border-radius:12px;overflow:hidden">
      <q-item v-for="r in sorted" :key="r.token"
        :class="r.stars != null && r.stars <= 2 ? 'bg-red-1' : (r.stars === 3 || r.stars === 4 ? 'bg-orange-1' : '')">
        <q-item-section avatar style="min-width:104px">
          <div class="text-h6" :style="{ color: r.stars >= 5 ? '#00C853' : (r.stars <= 2 ? '#e53935' : '#f5b50a'), letterSpacing: '1px' }">
            <span>{{ '★'.repeat(r.stars || 0) }}</span><span style="color:#e2e8f0">{{ '☆'.repeat(5 - (r.stars || 0)) }}</span>
          </div>
        </q-item-section>
        <q-item-section>
          <q-item-label class="text-weight-medium"><router-link v-if="r.customer" :to="'/clients/' + encodeURIComponent(r.customer)" class="erp-link">{{ r.name || r.customerName || r.customer || r.email || 'Client' }}</router-link><template v-else>{{ r.name || r.customerName || r.email || 'Client' }}</template></q-item-label>
          <q-item-label v-if="r.comment" class="q-mt-xs" style="white-space:pre-wrap;color:#334155">« {{ r.comment }} »</q-item-label>
          <q-item-label v-else caption class="text-grey-5">Aucun commentaire</q-item-label>
        </q-item-section>
        <q-item-section side top style="min-width:160px">
          <q-item-label caption>{{ formatDateTime(r.stars_ts || r.comment_ts || r.created) }}</q-item-label>
          <div class="q-gutter-xs q-mt-xs">
            <q-btn v-if="r.customer" dense flat size="sm" no-caps color="primary" icon="person" label="Fiche" @click="openFiche(r)" />
            <q-btn v-if="r.conv" dense flat size="sm" no-caps color="positive" icon="forum" label="Fil" @click="openThread(r)" />
            <q-btn v-if="r.customer || r.email" dense flat round size="sm" icon="forward_to_inbox" color="grey-6">
              <q-tooltip>Renvoyer l'invitation à évaluer (langue du client)</q-tooltip>
              <q-menu auto-close>
                <q-list dense style="min-width:190px">
                  <q-item-label header class="q-py-xs">Renvoyer l'invitation</q-item-label>
                  <q-item clickable @click="resend(r, 'email')"><q-item-section avatar><q-icon name="mail" color="primary" /></q-item-section><q-item-section>Par courriel</q-item-section></q-item>
                  <q-item clickable @click="resend(r, 'sms')"><q-item-section avatar><q-icon name="sms" color="positive" /></q-item-section><q-item-section>Par texto</q-item-section></q-item>
                </q-list>
              </q-menu>
            </q-btn>
            <q-btn v-if="r.customer || r.email" dense flat round size="sm" icon="edit_note" color="grey-6">
              <q-tooltip>Écrire au client (brouillon — utile pour un avis mécontent)</q-tooltip>
              <q-menu auto-close>
                <q-list dense style="min-width:190px">
                  <q-item-label header class="q-py-xs">Écrire au client</q-item-label>
                  <q-item clickable @click="draftFeedback(r, 'email')"><q-item-section avatar><q-icon name="mail" color="primary" /></q-item-section><q-item-section>Par courriel</q-item-section></q-item>
                  <q-item clickable @click="draftFeedback(r, 'sms')"><q-item-section avatar><q-icon name="sms" color="positive" /></q-item-section><q-item-section>Par texto</q-item-section></q-item>
                </q-list>
              </q-menu>
            </q-btn>
            <q-btn dense flat round size="sm" icon="delete" color="grey-5" @click="removeRating(r)"><q-tooltip>Supprimer (ex. avis de test)</q-tooltip></q-btn>
          </div>
        </q-item-section>
      </q-item>
    </q-list>
  </q-page>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useQuasar } from 'quasar'
import { HUB_URL } from 'src/config/hub'
import { formatDateTime } from 'src/composables/useFormatters'
import { useConversations } from 'src/composables/useConversations'
import DynamicFilter from 'src/components/shared/DynamicFilter.vue'

const router = useRouter()
const $q = useQuasar()
const { openComposeDraft } = useConversations()
const ratings = ref([])
const lowCount = ref(0)
const loading = ref(false)
const sortKey = ref('date')
const sortOptions = [
  { label: 'Date (plus récent)', value: 'date' },
  { label: 'Étoiles ↑ (basses d\'abord)', value: 'stars_asc' },
  { label: 'Étoiles ↓ (hautes d\'abord)', value: 'stars_desc' },
]
const dateOf = (r) => String(r.stars_ts || r.comment_ts || r.created || '')
// Filtre dynamique (client) : recherche client/commentaire + chips note (5★ / 3–4★ / ≤2★).
const filterState = ref({ search: '', chips: {} })
const chipGroups = [{ key: 'note', label: 'Note', icon: 'star', color: 'amber-7', options: [{ value: '5', label: '5★' }, { value: '34', label: '3–4★' }, { value: '12', label: '≤2★' }] }]
function matchNote (r) { const n = filterState.value.chips.note; if (!n) return true; const s = r.stars; if (n === '5') return s >= 5; if (n === '34') return s === 3 || s === 4; if (n === '12') return s != null && s <= 2; return true }
// Tout afficher + FILTRE (recherche/note) puis tri (date ou étoiles).
const sorted = computed(() => {
  const q = (filterState.value.search || '').toLowerCase().trim()
  const arr = ratings.value.filter(r => matchNote(r) && (!q || String(r.name || r.customerName || r.customer || r.email || '').toLowerCase().includes(q) || String(r.comment || '').toLowerCase().includes(q)))
  if (sortKey.value === 'stars_asc') arr.sort((a, b) => (a.stars ?? 99) - (b.stars ?? 99) || dateOf(b).localeCompare(dateOf(a)))
  else if (sortKey.value === 'stars_desc') arr.sort((a, b) => (b.stars ?? -1) - (a.stars ?? -1) || dateOf(b).localeCompare(dateOf(a)))
  else arr.sort((a, b) => dateOf(b).localeCompare(dateOf(a)))
  return arr
})

async function load () {
  loading.value = true
  try {
    const r = await fetch(HUB_URL + '/collab/ratings', { headers: { 'Content-Type': 'application/json' } })
    const d = r.ok ? await r.json() : {}
    ratings.value = d.ratings || []
    lowCount.value = d.low || 0
  } catch (e) { $q.notify({ type: 'negative', message: 'Échec du chargement des évaluations — réessayez.' }) } finally { loading.value = false }
}
function openFiche (r) { if (r.customer) router.push('/clients/' + encodeURIComponent(r.customer)) }
function openThread (r) { if (r.conv) router.push('/communications/c/' + encodeURIComponent(r.conv)) }
// Renvoyer l'invitation à évaluer (courriel/SMS) — le hub résout courriel/téléphone/langue depuis la fiche.
async function resend (r, channel) {
  try {
    const res = await fetch(HUB_URL + '/collab/send-rating-invite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ customer: r.customer || '', email: r.email || '', name: r.name || r.customerName || '', conv: r.conv || '', channel }) })
    const d = await res.json().catch(() => ({}))
    if (res.ok && d.ok !== false) $q.notify({ type: 'positive', icon: channel === 'sms' ? 'sms' : 'mail', message: `Invitation renvoyée par ${channel === 'sms' ? 'texto' : 'courriel'}${d.to ? ' → ' + d.to : ''}` })
    else $q.notify({ type: 'negative', message: d.error || "Échec de l'envoi" })
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) }
}
// Écrire au client (brouillon courriel/texto pré-rempli) — utile pour relancer un client mécontent.
async function draftFeedback (r, channel) {
  try {
    const qs = new URLSearchParams({ customer: r.customer || '', email: r.email || '', name: r.name || r.customerName || '', channel, kind: 'feedback' })
    const res = await fetch(HUB_URL + '/collab/rating-invite-draft?' + qs.toString())
    const d = res.ok ? await res.json() : {}
    if (!d.ok || !d.prefill) { $q.notify({ type: 'negative', message: d.error || 'Brouillon impossible' }); return }
    openComposeDraft(d.prefill)
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) }
}
// Supprimer une évaluation (avis de test) — confirmation puis retrait de la liste.
function removeRating (r) {
  $q.dialog({ title: 'Supprimer cette évaluation ?', message: 'Action définitive — utile pour retirer un avis de test.', cancel: true, ok: { label: 'Supprimer', color: 'negative' }, persistent: true }).onOk(async () => {
    try {
      const res = await fetch(HUB_URL + '/collab/ratings/' + encodeURIComponent(r.token), { method: 'DELETE' })
      const d = await res.json().catch(() => ({}))
      if (res.ok && d.ok) { ratings.value = ratings.value.filter(x => x.token !== r.token); lowCount.value = ratings.value.filter(x => x.stars != null && x.stars < 5).length; $q.notify({ type: 'positive', message: 'Évaluation supprimée' }) }
      else $q.notify({ type: 'negative', message: 'Suppression impossible' })
    } catch (e) { $q.notify({ type: 'negative', message: e.message }) }
  })
}
onMounted(load)
</script>
