<template>
  <!-- Contrôle REPORTER (report/mise en attente + fermeture rapide) partagé
       (page ticket · fiche client · Planification). C'est un menu de report/snooze,
       PAS un 2e sélecteur de statut : le statut canonique vit dans le select d'IssueDetail.
       Doctype-conscient : Issue (support) ou Dispatch Job (terrain). -->
  <q-btn-dropdown :label="label" dense no-caps unelevated :color="color" text-color="white" icon="schedule" :loading="busy">
    <q-list dense style="min-width:250px">
      <q-item-label header class="q-py-xs">⏰&nbsp; Reporter <HelpHint title="Reporter — mise en attente" text="Ce bouton reporte (snooze) ou ferme le billet ; ce n'est PAS le statut. Le statut se change dans le sélecteur du panneau de détail. « Reporter » repousse la date ; « En attente d'un autre ticket » met en pause jusqu'à la résolution d'un autre billet." /></q-item-label>
      <q-item clickable v-close-popup @click="postpone(1)"><q-item-section avatar><q-icon name="snooze" color="indigo" /></q-item-section><q-item-section>À demain (+1 jour)</q-item-section></q-item>
      <q-item clickable v-close-popup @click="postpone(7)"><q-item-section avatar><q-icon name="snooze" color="indigo" /></q-item-section><q-item-section>Dans 7 jours</q-item-section></q-item>
      <q-item clickable v-close-popup @click="postponeUntil"><q-item-section avatar><q-icon name="event" color="indigo" /></q-item-section><q-item-section>À une date précise…</q-item-section></q-item>
      <q-item clickable v-close-popup @click="waitTicket"><q-item-section avatar><q-icon name="hourglass_top" color="brown" /></q-item-section><q-item-section>En attente d'un autre ticket…</q-item-section></q-item>
      <q-separator class="q-my-xs" />
      <q-item v-if="!isClosed" clickable v-close-popup @click="close"><q-item-section avatar><q-icon name="check_circle" color="green-7" /></q-item-section><q-item-section>Fermer</q-item-section></q-item>
      <q-item v-else clickable v-close-popup @click="reopen"><q-item-section avatar><q-icon name="refresh" color="warning" /></q-item-section><q-item-section>Rouvrir</q-item-section></q-item>
    </q-list>
  </q-btn-dropdown>
</template>

<script setup>
import { computed, ref } from 'vue'
import { Dialog, Notify } from 'quasar'
import { updateDoc, createDoc } from 'src/api/erp'
import HelpHint from 'src/components/shared/HelpHint.vue'

const props = defineProps({
  doctype: { type: String, required: true }, // 'Issue' | 'Dispatch Job'
  docname: { type: String, required: true },
  status: { type: String, default: '' },
  scheduledDate: { type: String, default: '' },
})
const emit = defineEmits(['changed'])

const busy = ref(false)
const isJob = computed(() => props.doctype === 'Dispatch Job')
const isClosed = computed(() => ['Closed', 'Resolved', 'Completed', 'Cancelled'].includes(props.status))
const isHold = computed(() => props.status === 'On Hold')
const label = computed(() => isClosed.value ? 'Fermé' : (isHold.value ? 'En attente' : 'Reporter'))
const color = computed(() => isClosed.value ? 'grey-6' : (isHold.value ? 'brown' : 'primary'))

function todayPlus (days) { const d = new Date(); d.setDate(d.getDate() + Number(days || 0)); return d.toLocaleDateString('en-CA', { timeZone: 'America/Toronto' }) }

async function apply (patch, note) {
  busy.value = true
  try {
    await updateDoc(props.doctype, props.docname, patch)
    if (note) { try { await createDoc('Comment', { comment_type: 'Comment', reference_doctype: props.doctype, reference_name: props.docname, content: note }) } catch { /* note best-effort */ } }
    emit('changed', { ...patch, note })
    Notify.create({ type: 'positive', message: note || 'Statut mis à jour', timeout: 2200 })
  } catch (e) { Notify.create({ type: 'negative', message: 'Erreur: ' + e.message, timeout: 3000 }) }
  finally { busy.value = false }
}

// Reporter : job → replanifie à la date de réveil (+ On Hold) ; ticket → On Hold + note datée.
async function postpone (days) {
  const wake = todayPlus(days)
  if (isJob.value) apply({ scheduled_date: wake, status: 'On Hold' }, `⏰ Reporté au ${wake}`)
  else apply({ status: 'On Hold' }, `⏰ Reporté au ${wake}`)
}
function postponeUntil () {
  Dialog.create({ title: 'Reporter à…', prompt: { model: todayPlus(1), type: 'date' }, cancel: true, ok: { label: 'Reporter', color: 'primary' } })
    .onOk(v => { if (v) { if (isJob.value) apply({ scheduled_date: v, status: 'On Hold' }, `⏰ Reporté au ${v}`); else apply({ status: 'On Hold' }, `⏰ Reporté au ${v}`) } })
}
function waitTicket () {
  Dialog.create({ title: 'En attente d\'un autre ticket', message: 'N° du ticket bloquant (ex. 253907)', prompt: { model: '', type: 'text' }, cancel: true, ok: { label: 'Mettre en attente', color: 'brown' } })
    .onOk(v => { const num = String(v || '').trim(); if (num) apply({ status: 'On Hold' }, `⏳ En attente du ticket #${num}`) })
}
function close () { apply({ status: isJob.value ? 'Completed' : 'Closed' }, null) }
function reopen () { apply({ status: isJob.value ? 'open' : 'Open' }, null) }
</script>
