<template>
  <q-page class="q-pa-md">
    <div class="row items-center q-mb-md">
      <div>
        <div class="text-h6">Pool de récompenses</div>
        <div class="text-caption text-grey-7">Liens-cadeaux récupérés (jamais ouverts) — réattribuables à d'autres clients via notre lien intermédiaire.</div>
      </div>
      <q-space />
      <q-btn unelevated color="primary" icon="card_giftcard" label="Envoyer une récompense" :disable="pool.available === 0" @click="openSend" />
    </div>

    <div class="row q-col-gutter-md q-mb-md">
      <div class="col-12 col-sm-4">
        <q-card flat bordered><q-card-section><div class="text-caption text-grey-7">Disponibles</div><div class="text-h4 text-green-8">{{ pool.available }}</div></q-card-section></q-card>
      </div>
      <div class="col-12 col-sm-4">
        <q-card flat bordered><q-card-section><div class="text-caption text-grey-7">Réattribués</div><div class="text-h4">{{ pool.total - pool.available }}</div></q-card-section></q-card>
      </div>
      <div class="col-12 col-sm-4">
        <q-card flat bordered><q-card-section><div class="text-caption text-grey-7">Total récupérés</div><div class="text-h4">{{ pool.total }}</div></q-card-section></q-card>
      </div>
    </div>

    <DataTable flat bordered dense :rows="pool.items" :columns="cols" row-key="gift_url" :loading="loading" :pagination="{ rowsPerPage: 15 }">
      <template #body-cell-status="props">
        <q-td :props="props"><q-badge :color="props.row.used ? 'grey-6' : 'green'">{{ props.row.used ? 'Réattribué' : 'Disponible' }}</q-badge></q-td>
      </template>
      <template #body-cell-actions="props">
        <q-td :props="props">
          <q-btn v-if="props.row.used" flat dense size="sm" color="negative" icon="undo" no-caps label="Révoquer & remettre au pool" :loading="revoking === props.row.gift_url" @click="revokeRow(props.row)" />
        </q-td>
      </template>
      <template #no-data><div class="full-width text-center q-pa-md text-grey-7">Pool vide. Récupère des liens depuis l'inventaire des cadeaux.</div></template>
    </DataTable>

    <q-dialog v-model="send.open">
      <q-card style="min-width: 440px; max-width: 96vw">
        <q-card-section class="text-h6 row items-center"><q-icon name="card_giftcard" color="primary" class="q-mr-sm" />Envoyer une récompense</q-card-section>
        <q-separator />
        <q-card-section class="q-gutter-md">
          <q-select outlined dense use-input input-debounce="300" clearable
            label="Client — nom, courriel, téléphone…" v-model="send.customer"
            :options="custOptions" option-label="label" :loading="custSearching" @filter="searchCust"
            hint="Recherche auto-suggest">
            <template #no-option><q-item><q-item-section class="text-grey">Tapez au moins 2 caractères…</q-item-section></q-item></template>
          </q-select>

          <q-btn-toggle v-model="send.channel" dense unelevated toggle-color="primary" :options="[
            { label: 'Courriel', value: 'email', icon: 'mail' },
            { label: 'Texto (bientôt)', value: 'sms', icon: 'sms', disable: true }
          ]" />

          <q-banner v-if="send.preview" dense class="bg-blue-1 text-body2 rounded-borders">
            Aperçu → <b>{{ send.preview.would_send && send.preview.would_send.firstname }}</b>
            ({{ send.preview.would_send && send.preview.would_send.email }})<br>
            <span class="text-green-9">✓ Le client reçoit <b>notre</b> lien : <code style="font-size:11px">{{ send.preview.client_link }}</code></span><br>
            <span class="text-grey-7">Le lien Giftbit n'est jamais dans le courriel<span v-if="send.preview.raw_link_in_email === false"> (vérifié au rendu)</span>. Lien interne du pool, <b>non envoyé</b> : <code style="font-size:10px">{{ send.preview.pool_link_internal }}</code></span>
            · {{ send.preview.pool_available }} restant(s)
          </q-banner>
          <q-banner v-if="send.result" dense class="rounded-borders" :class="send.result.sent ? 'bg-green-1' : 'bg-red-1'">
            <span v-if="send.result.sent">✓ Envoyé. Lien suivi : <a :href="send.result.wrapper_url" target="_blank">{{ send.result.wrapper_url }}</a></span>
            <span v-else>{{ send.result.error || ('Statut : ' + send.result.status) }}</span>
          </q-banner>
          <div class="text-caption text-grey-7">Le courriel standard « récompense » est envoyé (prénom + lien préremplis). Le clic est suivi sur la fiche du client.</div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn flat label="Fermer" v-close-popup />
          <q-btn flat color="primary" label="Aperçu" :loading="send.busy" :disable="!send.customer" @click="doSend(true)" />
          <q-btn flat color="primary" icon="edit" label="Éditer dans la messagerie" :loading="send.busy" :disable="!send.customer" @click="doDraft" />
          <q-btn unelevated color="primary" label="Envoyer directement" :loading="send.busy" :disable="!send.customer" @click="doSend(false)" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import DataTable from 'src/components/shared/DataTable.vue'
import { useQuasar } from 'quasar'
import { useRouter } from 'vue-router'
import { HUB_URL } from 'src/config/hub'
import { getGiftPool, rewardSend, revokeReward } from 'src/api/campaigns'

const $q = useQuasar()
const router = useRouter()
const loading = ref(false)
const revoking = ref('')
const pool = reactive({ total: 0, available: 0, items: [] })
const cols = [
  { name: 'status', label: 'Statut', field: 'used', align: 'left' },
  { name: 'value', label: 'Valeur', field: r => (r.gift_value_cents ? (r.gift_value_cents / 100).toFixed(2) + ' $' : '—'), align: 'left' },
  { name: 'source', label: 'Source', field: 'source_campaign', align: 'left' },
  { name: 'reclaimed', label: 'Récupéré', field: r => (r.reclaimed_at || '').slice(0, 10), align: 'left' },
  { name: 'used_by', label: 'Réattribué à', field: r => r.used_by || '—', align: 'left' },
  { name: 'actions', label: '', field: 'gift_url', align: 'right' }
]

async function load () {
  loading.value = true
  try {
    const d = await getGiftPool()
    pool.total = d.total || 0
    pool.available = d.available || 0
    pool.items = d.items || []
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) } finally { loading.value = false }
}

const custOptions = ref([])
const custSearching = ref(false)
function searchCust (val, update) {
  const q = String(val || '').trim()
  if (q.length < 2) { update(() => { custOptions.value = [] }); return }
  custSearching.value = true
  fetch(`${HUB_URL}/collab/customer-search?q=${encodeURIComponent(q)}`)
    .then(r => (r.ok ? r.json() : {}))
    .then(d => {
      const opts = (d.matches || []).map(m => ({ label: (m.customer_name || m.name) + (m.email ? ' · ' + m.email : ''), id: m.name, email: m.email || '', name: m.customer_name || m.name }))
      update(() => { custOptions.value = opts })
    })
    .catch(() => update(() => { custOptions.value = [] }))
    .finally(() => { custSearching.value = false })
}

const send = reactive({ open: false, customer: null, channel: 'email', busy: false, preview: null, result: null })
function openSend () { send.open = true; send.customer = null; send.preview = null; send.result = null }
async function doSend (dryRun) {
  if (!send.customer) return
  send.busy = true
  send.preview = null
  if (!dryRun) send.result = null
  try {
    const r = await rewardSend({ customer_id: send.customer.id, email: send.customer.email, channel: send.channel, dry_run: dryRun })
    if (dryRun) {
      send.preview = r
      if (r.error) $q.notify({ type: 'warning', message: r.error })
    } else {
      send.result = r
      if (r.sent) { $q.notify({ type: 'positive', message: 'Récompense envoyée à ' + send.customer.name }); await load() } else { $q.notify({ type: 'negative', message: r.error || ('Échec : ' + r.status) }) }
    }
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) } finally { send.busy = false }
}

// Génère un brouillon (lien /g/ + prénom préremplis) et l'ouvre dans la messagerie centralisée pour édition + envoi.
async function doDraft () {
  if (!send.customer) return
  send.busy = true
  try {
    const r = await rewardSend({ customer_id: send.customer.id, email: send.customer.email, mode: 'draft' })
    if (r.error) { $q.notify({ type: 'negative', message: r.error }); return }
    if (r.conversation_token) {
      try {
        if (r.design) sessionStorage.setItem('reward_prefill_design_' + r.conversation_token, JSON.stringify(r.design))
        sessionStorage.setItem('reward_prefill_' + r.conversation_token, r.body_text || '')
      } catch (e) { /* */ }
      send.open = false
      $q.notify({ type: 'positive', message: 'Brouillon prêt — ouverture dans la messagerie' })
      await load()
      router.push('/communications/c/' + r.conversation_token)
    } else { $q.notify({ type: 'warning', message: 'Brouillon créé sans conversation' }) }
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) } finally { send.busy = false }
}

// Révoque une récompense envoyée + remet le lien au pool (refusé côté hub si déjà cliqué/redirigé).
async function revokeRow (row) {
  if (!window.confirm('Révoquer ce lien envoyé et le remettre au pool disponible ? Il cessera de fonctionner pour le client.')) return
  revoking.value = row.gift_url
  try {
    const r = await revokeReward(row.gift_url)
    if (r.error) $q.notify({ type: 'negative', message: r.error })
    else { $q.notify({ type: 'positive', message: 'Révoqué — lien remis au pool (' + r.available + ' disponibles)' }); await load() }
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) } finally { revoking.value = '' }
}

onMounted(load)
</script>
