<script setup>
/**
 * WeeklyScheduleEditor — génération de quarts HEBDO par tech, à partir de MODÈLES.
 * Reprend la meilleure UX (page Dispatch, qui sera supprimée) en Quasar + modèles partagés
 * (useHelpers.SCHEDULE_PRESETS) : chips de modèle → remplit le formulaire par jour (case + heures),
 * + « nombre de semaines » pour AUTOMATISER (répéter le patron sur N semaines).
 * Émet 'apply' { schedule:[{dow,on,start,end}] (Lun..Dim), weeks } → le parent écrit les Shift Assignment.
 */
import { reactive, ref, watch, computed } from 'vue'
import { SCHEDULE_PRESETS } from 'src/composables/useHelpers'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  techName: { type: String, default: '' },
  techs: { type: Array, default: () => [] }, // [{id,name}] — si >1 : sélection multi (application en LOT)
})
const emit = defineEmits(['update:modelValue', 'apply'])

const DAYS = [['mon', 'Lun'], ['tue', 'Mar'], ['wed', 'Mer'], ['thu', 'Jeu'], ['fri', 'Ven'], ['sat', 'Sam'], ['sun', 'Dim']]
const sched = reactive({})
const weeks = ref(1)
const mode = ref('recurring') // 'recurring' = patron de base (matérialisé, exceptions auto) · 'exception' = override ponctuel (semaines précises)
const selected = ref(new Set()) // techIds cochés (mode lot)
const bulk = computed(() => (props.techs || []).length > 1)
const title = computed(() => bulk.value ? ((props.techs || []).length + ' techniciens') : (props.techName || (props.techs[0] && props.techs[0].name) || ''))

function fill (preset) { for (const [k] of DAYS) { const s = preset[k]; sched[k] = s ? { on: true, start: s.start, end: s.end } : { on: false, start: '08:00', end: '16:00' } } }
fill(SCHEDULE_PRESETS[0].schedule)
watch(() => props.modelValue, (o) => { if (o) { fill(SCHEDULE_PRESETS[0].schedule); weeks.value = mode.value === 'recurring' ? 6 : 1; selected.value = new Set((props.techs || []).map(t => t.id)) } })
watch(mode, (m) => { weeks.value = m === 'recurring' ? 6 : 1 })
function toggleTech (id) { const s = new Set(selected.value); s.has(id) ? s.delete(id) : s.add(id); selected.value = s }
// Sélection des techs (mode lot) : recherche par nom · sélection par compétence · tout / aucun
const techSearch = ref('')
const allSkills = computed(() => { const s = new Set(); for (const t of (props.techs || [])) for (const sk of (t.skills || [])) s.add(sk); return [...s].sort() })
const filteredTechs = computed(() => { const q = techSearch.value.trim().toLowerCase(); return q ? (props.techs || []).filter(t => String(t.name || '').toLowerCase().includes(q)) : (props.techs || []) })
function selectAllShown () { const s = new Set(selected.value); for (const t of filteredTechs.value) s.add(t.id); selected.value = s }
function selectNone () { selected.value = new Set() }
function selectBySkill (sk) { const s = new Set(selected.value); for (const t of (props.techs || [])) if ((t.skills || []).includes(sk)) s.add(t.id); selected.value = s }

function dayHours (d) { if (!d || !d.on) return 0; const [h1, m1] = d.start.split(':').map(Number); const [h2, m2] = d.end.split(':').map(Number); let mn = (h2 * 60 + m2) - (h1 * 60 + m1); if (mn < 0) mn += 1440; return Math.round(mn / 60 * 10) / 10 }
const totalDays = () => DAYS.filter(([k]) => sched[k]?.on).length
const totalHours = () => DAYS.reduce((s, [k]) => s + dayHours(sched[k]), 0)
function submit () {
  const techIds = bulk.value ? [...selected.value] : (props.techs[0] ? [props.techs[0].id] : [])
  if (!techIds.length) return
  emit('apply', { schedule: DAYS.map(([k]) => ({ dow: k, ...sched[k] })), weeks: Math.max(1, Math.min(12, Number(weeks.value) || 1)), techIds, mode: mode.value })
  emit('update:modelValue', false)
}
</script>

<template>
  <q-dialog :model-value="modelValue" @update:model-value="v => emit('update:modelValue', v)">
    <q-card style="width:600px;max-width:96vw">
      <q-card-section class="row items-center q-pb-sm">
        <q-icon name="event_note" color="primary" size="24px" class="q-mr-sm" />
        <div class="text-h6">Horaire — {{ title }}</div>
        <q-space /><q-btn flat round dense icon="close" @click="emit('update:modelValue', false)" />
      </q-card-section>
      <q-separator />
      <q-card-section class="q-gutter-sm">
        <!-- Mode : patron RÉCURRENT (base, matérialisé avec fériés/vacances sautés) vs EXCEPTION ponctuelle (semaines précises) -->
        <q-btn-toggle v-model="mode" spread no-caps dense unelevated toggle-color="primary" color="grey-3" text-color="grey-8"
          :options="[{ value: 'recurring', slot: 'rec' }, { value: 'exception', slot: 'exc' }]">
          <template #rec><div class="column items-center" style="line-height:1.1;padding:2px 0"><span>🔁 Horaire récurrent</span><span style="font-size:10px;opacity:.7">base · fériés/vacances sautés</span></div></template>
          <template #exc><div class="column items-center" style="line-height:1.1;padding:2px 0"><span>📌 Exception</span><span style="font-size:10px;opacity:.7">semaine(s) précise(s)</span></div></template>
        </q-btn-toggle>
        <!-- Mode LOT : choisir les techniciens à qui appliquer le modèle (tous cochés par défaut) -->
        <div v-if="bulk">
          <div class="row items-center q-mb-xs">
            <div class="text-caption text-grey-7">Appliquer à <b>{{ selected.size }}</b>/{{ techs.length }}</div>
            <q-space />
            <q-btn flat dense no-caps size="sm" color="primary" label="Tout" @click="selectAllShown" />
            <q-btn flat dense no-caps size="sm" color="grey-7" label="Aucun" @click="selectNone" />
          </div>
          <q-input v-model="techSearch" dense outlined clearable placeholder="Chercher un nom…" class="q-mb-xs">
            <template #prepend><q-icon name="search" size="18px" /></template>
          </q-input>
          <div v-if="allSkills.length" class="row q-gutter-xs q-mb-xs items-center">
            <span class="text-caption text-grey-6">Par compétence :</span>
            <span v-for="sk in allSkills" :key="sk" class="wse-skill" @click="selectBySkill(sk)"><q-icon name="add" size="11px" />{{ sk }}</span>
          </div>
          <div class="row q-gutter-xs" style="max-height:120px;overflow:auto">
            <span v-for="t in filteredTechs" :key="t.id" class="wse-tech" :class="{ on: selected.has(t.id) }" @click="toggleTech(t.id)">
              <q-icon :name="selected.has(t.id) ? 'check' : 'add'" size="12px" />{{ t.name }}
            </span>
            <div v-if="!filteredTechs.length" class="text-caption text-grey-5 q-pa-xs">Aucun tech pour « {{ techSearch }} »</div>
          </div>
        </div>
        <!-- Modèles (1 clic remplit le formulaire) -->
        <div class="row q-gutter-xs">
          <span v-for="p in SCHEDULE_PRESETS" :key="p.key" class="wse-preset" @click="fill(p.schedule)">{{ p.label }}</span>
        </div>
        <!-- Jours -->
        <div class="wse-grid">
          <div v-for="[k, lbl] in DAYS" :key="k" class="wse-day" :class="{ off: !sched[k]?.on }">
            <q-checkbox dense v-model="sched[k].on" :label="lbl" class="wse-day-lbl" />
            <template v-if="sched[k]?.on">
              <input type="time" v-model="sched[k].start" class="wse-time" />
              <span class="wse-sep">→</span>
              <input type="time" v-model="sched[k].end" class="wse-time" />
              <span class="wse-h">{{ dayHours(sched[k]) }}h</span>
            </template>
            <span v-else class="wse-repos">Repos</span>
          </div>
        </div>
        <!-- Horizon : récurrent = fenêtre à matérialiser ; exception = nb de semaines dès la semaine affichée -->
        <div class="row items-center q-gutter-sm q-pt-xs">
          <q-input dense outlined type="number" v-model.number="weeks" :label="mode === 'recurring' ? 'Matérialiser N semaines' : 'N semaine(s) dès la semaine affichée'" :min="1" :max="12" style="width:250px">
            <template #prepend><q-icon name="repeat" size="18px" /></template>
          </q-input>
          <div class="text-caption text-grey-6">{{ totalDays() }} j / {{ Math.round(totalHours() * 10) / 10 }}h par semaine</div>
        </div>
        <div class="text-caption text-grey-6">{{ mode === 'recurring' ? 'Devient l\'horaire par défaut : quarts générés automatiquement, fériés & vacances exclus, tes ajustements manuels préservés.' : 'Écrit des quarts pour ces semaines uniquement (override) — ex. semaine de nuit. Ne change pas l\'horaire de base.' }}</div>
      </q-card-section>
      <q-card-actions align="right" class="q-px-md q-pb-md">
        <q-btn flat no-caps label="Annuler" color="grey-7" @click="emit('update:modelValue', false)" />
        <q-btn unelevated no-caps color="primary" icon="event_available" :disable="bulk && !selected.size" :label="(mode === 'recurring' ? 'Définir l\'horaire' : 'Créer l\'exception') + (bulk ? ' ×' + selected.size + ' tech' : '')" @click="submit" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.wse-preset { display: inline-flex; align-items: center; padding: 4px 12px; border: 1.5px solid #c7d2fe; border-radius: 14px; font-size: 12.5px; font-weight: 600; color: #4338ca; background: #eef2ff; cursor: pointer; user-select: none; }
.wse-preset:hover { background: #e0e7ff; }
.wse-grid { display: flex; flex-direction: column; gap: 4px; }
.wse-day { display: flex; align-items: center; gap: 8px; padding: 4px 8px; border-radius: 8px; background: #f8fafc; }
.wse-day.off { opacity: 0.7; }
.wse-day-lbl { min-width: 62px; font-weight: 600; }
.wse-time { border: 1px solid #cbd5e1; border-radius: 6px; padding: 3px 6px; font-size: 13px; font-family: inherit; }
.wse-sep { color: #94a3b8; }
.wse-h { color: #64748b; font-size: 12px; font-weight: 600; margin-left: auto; }
.wse-repos { color: #94a3b8; font-style: italic; font-size: 12.5px; margin-left: 8px; }
.wse-tech { display: inline-flex; align-items: center; gap: 3px; padding: 2px 9px; border: 1.5px solid #cbd5e1; border-radius: 12px; font-size: 12px; font-weight: 600; color: #64748b; background: #fff; cursor: pointer; user-select: none; }
.wse-tech.on { border-color: #6366f1; background: #eef2ff; color: #4338ca; }
.wse-skill { display: inline-flex; align-items: center; gap: 2px; padding: 2px 8px; border: 1px dashed #94a3b8; border-radius: 12px; font-size: 11px; font-weight: 600; color: #475569; background: #f8fafc; cursor: pointer; user-select: none; }
.wse-skill:hover { border-color: #6366f1; color: #4338ca; background: #eef2ff; }
</style>
