<template>
  <q-drawer v-model="panelOpen" side="right" :width="400" bordered overlay class="conv-panel">
    <!-- List view (discussions) -->
    <template v-if="!activeDiscussion">
      <q-toolbar class="conv-toolbar">
        <q-toolbar-title class="text-weight-bold" style="font-size:0.95rem">
          Discussions
          <q-badge v-if="activeCount" color="indigo-6" class="q-ml-xs">{{ activeCount }}</q-badge>
        </q-toolbar-title>
        <q-btn flat round dense :icon="showAll ? 'filter_alt_off' : 'filter_alt'" size="sm"
          :color="showAll ? 'indigo-6' : 'grey-6'" @click="showAll = !showAll; fetchList()">
          <q-tooltip>{{ showAll ? 'Actives seulement' : 'Voir tout' }}</q-tooltip>
        </q-btn>
        <q-btn flat round dense icon="add" size="sm" @click="showNewDialog = true">
          <q-tooltip>Nouvelle conversation</q-tooltip>
        </q-btn>
        <q-btn flat round dense icon="refresh" size="sm" :loading="loading" @click="fetchList" />
        <q-btn flat round dense icon="close" size="sm" @click="panelOpen = false" />
      </q-toolbar>

      <!-- Bulk action bar -->
      <div v-if="selectedIds.size > 0" class="bulk-bar">
        <q-checkbox :model-value="selectedIds.size === discussions.length" @update:model-value="v => v ? selectAll() : clearSelection()"
          dense size="sm" class="q-mr-xs" :indeterminate-value="true"
          :true-value="true" :false-value="false" />
        <span class="text-caption text-weight-medium">{{ selectedIds.size }} selectionne{{ selectedIds.size > 1 ? 's' : '' }}</span>
        <q-space />
        <q-btn flat dense size="sm" icon="archive" color="indigo-6" :loading="archiving" @click="doBulkArchive">
          <q-tooltip>Archiver en tickets</q-tooltip>
        </q-btn>
        <q-btn flat dense size="sm" icon="delete_outline" color="red-5" :loading="bulkDeleting" @click="doBulkDelete">
          <q-tooltip>Supprimer</q-tooltip>
        </q-btn>
        <q-btn flat dense size="sm" icon="close" color="grey-6" @click="clearSelection" />
      </div>

      <q-list v-if="discussions.length" separator class="disc-list">
        <q-item v-for="d in discussions" :key="d.id" clickable
          :class="{ 'bg-blue-1': d.lastMessage?.from === 'customer' && d.status === 'active', 'bg-indigo-1': selectedIds.has(d.id) }">
          <q-item-section avatar style="min-width:auto;padding-right:4px">
            <q-checkbox :model-value="selectedIds.has(d.id)" @update:model-value="toggleSelect(d.id)"
              dense size="sm" @click.stop />
          </q-item-section>
          <q-item-section @click="openDiscussion(d)">
            <q-item-label class="text-weight-medium" style="font-size:0.85rem">
              {{ d.customerName || d.phone }}
              <q-badge v-if="d.status === 'active'" color="green" class="q-ml-xs" style="font-size:0.55rem;padding:1px 4px;">actif</q-badge>
            </q-item-label>
            <q-item-label caption lines="1">
              <span v-if="d.lastMessage" :class="{ 'text-weight-medium': d.lastMessage.from === 'customer' }">
                <template v-if="d.lastMessage.from === 'customer'">Client: </template>
                <template v-else-if="d.lastMessage.from === 'agent' && d.lastMessage.via === 'ai'">AI: </template>
                {{ d.lastMessage.text }}
              </span>
              <span v-else>Aucun message</span>
            </q-item-label>
          </q-item-section>
          <q-item-section side top @click="openDiscussion(d)">
            <q-item-label caption>{{ formatDate(d.date) }}</q-item-label>
            <q-badge :color="d.status === 'active' ? 'green' : 'grey-4'" :text-color="d.status === 'active' ? 'white' : 'grey-6'"
              style="font-size:0.6rem;padding:1px 4px;">
              {{ d.messageCount }} msg
            </q-badge>
          </q-item-section>
        </q-item>
      </q-list>
      <div v-else-if="!loading" class="q-pa-lg text-center text-grey-5">
        <q-icon name="chat_bubble_outline" size="40px" class="q-mb-sm" /><br>
        Aucune discussion
      </div>
    </template>

    <!-- Discussion detail: merged message thread -->
    <template v-else>
      <q-toolbar class="conv-toolbar">
        <q-btn flat round dense icon="arrow_back" size="sm" @click="goBack" />
        <q-toolbar-title style="font-size:0.9rem">
          <div class="text-weight-bold">{{ activeDiscussion.customerName || activeDiscussion.phone }}</div>
          <div class="text-caption text-grey-6">{{ formatDate(activeDiscussion.date) }} &middot; {{ activeDiscussion.messageCount }} messages</div>
        </q-toolbar-title>
        <q-btn flat dense size="sm" icon="archive" color="indigo-6" :loading="archiving" @click="doArchive(activeDiscussion)">
          <q-tooltip>Archiver en ticket</q-tooltip>
        </q-btn>
        <q-btn flat dense size="sm" icon="delete_outline" color="red-5" @click="confirmDeleteDiscussion(activeDiscussion)">
          <q-tooltip>Supprimer</q-tooltip>
        </q-btn>
        <q-btn v-if="activeToken && activeDiscussion.status === 'active'" flat dense size="sm" icon="stop_circle" color="orange-7"
          @click="confirmClose">
          <q-tooltip>Fermer la session</q-tooltip>
        </q-btn>
      </q-toolbar>

      <div ref="messagesEl" class="conv-messages">
        <div v-for="msg in activeDiscussion.messages" :key="msg.id" class="conv-msg" :class="'conv-msg-' + msg.from">
          <div class="conv-bubble">
            <div class="conv-sender" v-if="msg.from === 'agent' && msg.via === 'ai'">AI Assistant</div>
            <div class="conv-text">{{ msg.text }}</div>
            <div class="conv-meta">
              <span v-if="msg.via === 'sms'" class="conv-via">SMS</span>
              <span v-else-if="msg.via === 'ai'" class="conv-via ai">AI</span>
              {{ formatTime(msg.ts) }}
            </div>
          </div>
        </div>
      </div>

      <div v-if="activeToken && activeDiscussion.status === 'active'" class="conv-compose">
        <q-input v-model="draft" dense outlined placeholder="Repondre..." autogrow
          :input-style="{ fontSize: '0.85rem' }"
          @keydown.enter.exact.prevent="send">
          <template #append>
            <q-btn flat round dense icon="send" color="indigo-6" size="sm"
              :disable="!draft.trim()" :loading="sending" @click="send" />
          </template>
        </q-input>
      </div>
      <div v-else class="q-pa-sm text-center text-grey-5 text-caption" style="border-top:1px solid #e2e8f0">
        Discussion terminee
      </div>
    </template>

    <!-- New conversation dialog -->
    <q-dialog v-model="showNewDialog">
      <q-card style="min-width:340px">
        <q-card-section class="text-weight-bold">Nouvelle conversation</q-card-section>
        <q-card-section class="q-pt-none">
          <q-input v-model="newPhone" dense outlined label="Telephone" class="q-mb-sm" />
          <q-input v-model="newCustomer" dense outlined label="Client ID (optionnel)" class="q-mb-sm" />
          <q-input v-model="newCustomerName" dense outlined label="Nom du client" class="q-mb-sm" />
          <q-input v-model="newSubject" dense outlined label="Sujet" />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="Annuler" v-close-popup />
          <q-btn unelevated color="indigo-6" label="Envoyer le lien" :disable="!newPhone.trim() || creating"
            :loading="creating" @click="createNew" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-drawer>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useQuasar } from 'quasar'
import { useConversations } from 'src/composables/useConversations'

const $q = useQuasar()
const {
  discussions, activeToken, activeDiscussion, loading, panelOpen, showAll, activeCount,
  selectedIds, selectedDiscussions,
  fetchList, openDiscussion, sendMessage, startConversation, closeConversation,
  deleteDiscussion, bulkDelete, archiveDiscussion, bulkArchive,
  toggleSelect, selectAll, clearSelection,
  goBack, disconnectSSE, connectGlobalSSE,
} = useConversations()

const draft = ref('')
const sending = ref(false)
const messagesEl = ref(null)
const archiving = ref(false)
const bulkDeleting = ref(false)

const showNewDialog = ref(false)
const newPhone = ref('')
const newCustomer = ref('')
const newCustomerName = ref('')
const newSubject = ref('')
const creating = ref(false)

onMounted(() => {
  fetchList()
  connectGlobalSSE()
})

onUnmounted(() => {
  disconnectSSE()
})

async function send () {
  const text = draft.value.trim()
  if (!text || !activeToken.value) return
  sending.value = true
  try {
    await sendMessage(activeToken.value, text)
    draft.value = ''
    await nextTick()
    scrollToBottom()
  } catch {
    $q.notify({ type: 'negative', message: 'Erreur d\'envoi' })
  }
  sending.value = false
}

async function createNew () {
  creating.value = true
  try {
    await startConversation({
      phone: newPhone.value.trim(),
      customer: newCustomer.value.trim() || undefined,
      customerName: newCustomerName.value.trim() || undefined,
      subject: newSubject.value.trim() || undefined,
    })
    showNewDialog.value = false
    newPhone.value = ''; newCustomer.value = ''; newCustomerName.value = ''; newSubject.value = ''
    $q.notify({ type: 'positive', message: 'Lien envoye par SMS' })
  } catch {
    $q.notify({ type: 'negative', message: 'Erreur de creation' })
  }
  creating.value = false
}

function confirmClose () {
  $q.dialog({
    title: 'Fermer la session ?',
    message: 'Le client ne pourra plus envoyer de messages dans cette session.',
    cancel: { flat: true, label: 'Annuler' },
    ok: { color: 'orange', label: 'Fermer' },
  }).onOk(async () => {
    await closeConversation(activeToken.value)
  })
}

function confirmDeleteDiscussion (disc) {
  $q.dialog({
    title: 'Supprimer la discussion ?',
    message: `Supprimer ${disc.messageCount} messages avec ${disc.customerName || disc.phone} ?`,
    cancel: { flat: true, label: 'Annuler' },
    ok: { color: 'red', label: 'Supprimer' },
  }).onOk(async () => {
    try {
      await deleteDiscussion(disc)
      $q.notify({ type: 'positive', message: 'Discussion supprimee' })
    } catch {
      $q.notify({ type: 'negative', message: 'Erreur de suppression' })
    }
  })
}

async function doArchive (disc) {
  $q.dialog({
    title: 'Archiver en ticket ?',
    message: `Creer un ticket ferme avec les ${disc.messageCount} messages, puis supprimer la discussion ?`,
    cancel: { flat: true, label: 'Annuler' },
    ok: { color: 'indigo', label: 'Archiver' },
  }).onOk(async () => {
    archiving.value = true
    try {
      const result = await archiveDiscussion(disc)
      $q.notify({ type: 'positive', message: `Archive → ticket ${result.issue}` })
      goBack()
    } catch (e) {
      $q.notify({ type: 'negative', message: e.message || 'Erreur d\'archivage' })
    }
    archiving.value = false
  })
}

async function doBulkArchive () {
  const sel = selectedDiscussions.value
  $q.dialog({
    title: `Archiver ${sel.length} discussion${sel.length > 1 ? 's' : ''} ?`,
    message: `Un ticket ferme sera cree pour chaque discussion.`,
    cancel: { flat: true, label: 'Annuler' },
    ok: { color: 'indigo', label: 'Archiver tout' },
  }).onOk(async () => {
    archiving.value = true
    try {
      const results = await bulkArchive(sel)
      $q.notify({ type: 'positive', message: `${results.length} discussion${results.length > 1 ? 's' : ''} archivee${results.length > 1 ? 's' : ''}` })
    } catch {
      $q.notify({ type: 'negative', message: 'Erreur d\'archivage' })
    }
    archiving.value = false
  })
}

async function doBulkDelete () {
  const sel = selectedDiscussions.value
  const totalMsgs = sel.reduce((n, d) => n + d.messageCount, 0)
  $q.dialog({
    title: `Supprimer ${sel.length} discussion${sel.length > 1 ? 's' : ''} ?`,
    message: `${totalMsgs} messages seront supprimees definitivement.`,
    cancel: { flat: true, label: 'Annuler' },
    ok: { color: 'red', label: 'Supprimer tout' },
  }).onOk(async () => {
    bulkDeleting.value = true
    try {
      await bulkDelete(sel)
      $q.notify({ type: 'positive', message: `${sel.length} discussions supprimees` })
    } catch {
      $q.notify({ type: 'negative', message: 'Erreur de suppression' })
    }
    bulkDeleting.value = false
  })
}

function scrollToBottom () {
  if (messagesEl.value) messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}

watch(() => activeDiscussion.value?.messages?.length, () => nextTick(() => scrollToBottom()))

function formatTime (ts) {
  if (!ts) return ''
  const d = new Date(ts)
  const now = new Date()
  if (d.toDateString() === now.toDateString()) return d.toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString('fr-CA', { month: 'short', day: 'numeric' }) + ' ' + d.toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit' })
}

function formatDate (dateStr) {
  if (!dateStr) return ''
  const d = new Date(dateStr + 'T00:00:00')
  const now = new Date()
  const today = now.toISOString().slice(0, 10)
  const yesterday = new Date(now - 86400000).toISOString().slice(0, 10)
  if (dateStr === today) return "Aujourd'hui"
  if (dateStr === yesterday) return 'Hier'
  return d.toLocaleDateString('fr-CA', { weekday: 'short', month: 'short', day: 'numeric' })
}
</script>

<style scoped>
.conv-toolbar {
  background: #fff;
  border-bottom: 1px solid #e2e8f0;
  min-height: 48px;
}
.bulk-bar {
  display: flex;
  align-items: center;
  padding: 4px 10px;
  background: #eef2ff;
  border-bottom: 1px solid #c7d2fe;
}
.disc-list .q-item { padding: 6px 8px; }

.conv-messages {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 6px;
  height: calc(100vh - 100px);
}
.conv-msg { display: flex; }
.conv-msg-customer { justify-content: flex-start; }
.conv-msg-agent { justify-content: flex-end; }
.conv-msg-system { justify-content: center; }

.conv-bubble { max-width: 85%; padding: 8px 12px; border-radius: 12px; font-size: 0.85rem; line-height: 1.4; word-break: break-word; }
.conv-msg-customer .conv-bubble { background: #f1f5f9; color: #1e293b; border-bottom-left-radius: 3px; }
.conv-msg-agent .conv-bubble { background: #4f46e5; color: #fff; border-bottom-right-radius: 3px; }
.conv-msg-system .conv-bubble { background: transparent; color: #94a3b8; font-size: 0.75rem; }

.conv-sender { font-size: 0.65rem; font-weight: 600; opacity: 0.7; margin-bottom: 2px; }
.conv-meta { font-size: 0.65rem; opacity: 0.6; margin-top: 3px; text-align: right; }
.conv-via { background: rgba(0,0,0,0.08); padding: 1px 3px; border-radius: 2px; font-size: 0.6rem; margin-right: 3px; }
.conv-msg-agent .conv-via { background: rgba(255,255,255,0.2); }
.conv-via.ai { background: rgba(255,255,255,0.25); }

.conv-compose { padding: 8px 10px; border-top: 1px solid #e2e8f0; background: #fff; }
</style>
