<template>
  <q-dialog v-model="open">
    <q-card style="min-width:680px">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-subtitle1 text-weight-bold">Congés &amp; disponibilités</div><q-space />
        <q-select dense outlined v-model="leaveFilter" :options="['Demandé', 'Approuvé', 'Refusé', '']" style="width:130px" @update:model-value="loadLeave" />
        <q-btn flat round dense icon="close" v-close-popup class="q-ml-sm" />
      </q-card-section>
      <q-card-section>
        <table class="demand-tbl" style="width:100%">
          <thead><tr><th>Technicien</th><th>Type</th><th>Du</th><th>Au</th><th>Motif</th><th>Statut</th><th></th></tr></thead>
          <tbody>
            <tr v-for="l in leaveRows" :key="l.name">
              <td>{{ l.technician_name || l.technician }}</td><td>{{ l.availability_type }}</td><td>{{ l.from_date }}</td><td>{{ l.to_date }}</td><td>{{ l.reason }}</td>
              <td><q-badge :color="l.status === 'Approuvé' ? 'green' : l.status === 'Refusé' ? 'red' : 'orange'">{{ l.status }}</q-badge></td>
              <td><template v-if="l.status === 'Demandé'"><q-btn flat dense round size="sm" icon="check" color="green" @click="approveLeave(l, false)" /><q-btn flat dense round size="sm" icon="close" color="red" @click="approveLeave(l, true)" /></template></td>
            </tr>
            <tr v-if="!leaveRows.length"><td colspan="7" class="text-grey-6 q-pa-sm">Aucune demande.</td></tr>
          </tbody>
        </table>
        <q-separator class="q-my-md" />
        <div class="text-caption text-weight-bold q-mb-xs">Nouvelle demande</div>
        <div class="row items-center q-gutter-sm">
          <TechSelect v-model="newLeave.technician" :options="techOptions" label="Technicien" style="width:200px" />
          <q-select dense outlined v-model="newLeave.availability_type" :options="['Congé', 'Pause', 'Indisponible', 'Maladie']" label="Type" style="width:130px" />
          <q-input dense outlined type="date" v-model="newLeave.from_date" label="Du" style="width:140px" />
          <q-input dense outlined type="date" v-model="newLeave.to_date" label="Au" style="width:140px" />
          <q-input dense outlined v-model="newLeave.reason" label="Motif" style="width:150px" />
          <q-toggle dense v-model="newLeave.long_term" :true-value="1" :false-value="0" label="Longue durée"><q-tooltip>Maternité, invalidité… → à remplacer (pas juste sauter comme des vacances)</q-tooltip></q-toggle>
          <q-btn dense unelevated color="primary" icon="add" label="Créer" @click="createLeave" />
        </div>
        <div class="text-caption text-grey-7 q-mt-sm">Une demande <b>approuvée</b> rend le tech indisponible pour le solveur sur ces dates.</div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
// Dialogue « Congés & disponibilités » — extrait de PlanificationPage (décomposition #4).
// Auto-contenu : état PRIVÉ (leaveRows/leaveFilter/newLeave) + API roster ; AUCUNE mutation
// de l'état partagé de la page (pas de loadWeek → ne peut pas désynchroniser la grille).
// S'ouvre via v-model (le menu Outils fait `showLeave = true`) et charge à l'ouverture.
import { ref, reactive, computed, watch } from 'vue'
import { useQuasar } from 'quasar'
import * as roster from 'src/api/roster'
import TechSelect from 'src/components/shared/TechSelect.vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false }, // ouverture (v-model)
  techs: { type: Array, default: () => [] },       // lecture seule (résolution du nom au création)
  techOptions: { type: Array, default: () => [] }, // lecture seule (sélecteur)
})
const emit = defineEmits(['update:modelValue'])
const $q = useQuasar()
const err = (e) => $q.notify({ type: 'negative', message: '' + (e.message || e) })

const open = computed({ get: () => props.modelValue, set: v => emit('update:modelValue', v) })
const leaveRows = ref([])
const leaveFilter = ref('Demandé')
const newLeave = reactive({ technician: '', availability_type: 'Congé', from_date: '', to_date: '', reason: '', long_term: 0 })

async function loadLeave () { try { leaveRows.value = (await roster.listAvailability(leaveFilter.value)).availability || [] } catch (e) { err(e) } }
async function approveLeave (l, reject) { try { await roster.approveAvailability(l.name, { reject, approver: 'ops' }); $q.notify({ type: reject ? 'info' : 'positive', message: (l.technician_name || l.technician) + (reject ? ' refusé' : ' approuvé') }); await loadLeave() } catch (e) { err(e) } }
async function createLeave () {
  if (!newLeave.technician || !newLeave.from_date || !newLeave.to_date) { $q.notify({ type: 'warning', message: 'Technicien + dates requis' }); return }
  const t = props.techs.find(x => x.id === newLeave.technician)
  try { await roster.requestAvailability({ technician: newLeave.technician, technician_name: t ? t.name : '', availability_type: newLeave.availability_type, from_date: newLeave.from_date, to_date: newLeave.to_date, reason: newLeave.reason, long_term: newLeave.long_term }); $q.notify({ type: 'positive', message: 'Demande créée' }); newLeave.from_date = ''; newLeave.to_date = ''; newLeave.reason = ''; newLeave.long_term = 0; await loadLeave() } catch (e) { err(e) }
}
// Charger à l'ouverture (remplace l'ancien openLeave de la page).
watch(() => props.modelValue, (v) => { if (v) loadLeave() })
</script>

<style scoped>
/* Copié de PlanificationPage (le CSS scoped ne traverse pas vers l'enfant). */
.demand-tbl { border-collapse: collapse; width: 100%; }
.demand-tbl th { font-size: 11px; color: #888; font-weight: 600; padding: 2px 6px; text-align: left; }
.demand-tbl td { padding: 2px 4px; }
</style>
