<template>
  <q-dialog v-model="open" @show="onShow">
    <q-card style="min-width:420px;max-width:520px">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">{{ mode === 'link' ? 'Lier un profil employé' : 'Profil employé' }}</div>
        <q-space />
        <q-btn flat round dense icon="close" v-close-popup />
      </q-card-section>

      <q-card-section v-if="loading" class="column items-center q-py-lg">
        <q-spinner size="28px" color="primary" /><div class="text-caption text-grey-6 q-mt-sm">Chargement…</div>
      </q-card-section>

      <!-- MODE LIEN : aucun employé lié à ce compte → choisir un employé existant -->
      <q-card-section v-else-if="mode === 'link'">
        <div class="text-caption text-grey-7 q-mb-sm">
          Aucun profil employé lié à <b>{{ linkEmail }}</b>. Choisissez l'employé correspondant :
          on renseignera son <code>user_id</code> pour établir le lien.
        </div>
        <q-select v-model="linkTarget" :options="empOptions" use-input input-debounce="300"
          outlined dense label="Rechercher un employé…" option-label="employee_name" option-value="name"
          @filter="filterEmployees" :loading="empSearching" clearable>
          <template #option="scope">
            <q-item v-bind="scope.itemProps">
              <q-item-section><q-item-label>{{ scope.opt.employee_name }}</q-item-label>
                <q-item-label caption>{{ scope.opt.name }}<span v-if="scope.opt.user_id"> · déjà lié à {{ scope.opt.user_id }}</span></q-item-label></q-item-section>
            </q-item>
          </template>
        </q-select>
      </q-card-section>

      <!-- MODE ÉDITION : champs de l'employé + lien de connexion -->
      <q-card-section v-else class="q-gutter-sm">
        <q-input v-model="form.employee_name" label="Nom (RH)" outlined dense :disable="saving" />
        <q-select v-model="form.designation" :options="designationOpts" label="Poste" outlined dense
          use-input input-debounce="0" @filter="filterDesignations" clearable emit-value map-options :disable="saving" />
        <q-select v-model="form.department" :options="departmentOpts" label="Département" outlined dense
          use-input input-debounce="0" @filter="filterDepartments" clearable emit-value map-options :disable="saving" />
        <div class="row q-col-gutter-sm">
          <q-input class="col" v-model="form.cell_number" label="Téléphone" outlined dense :disable="saving" />
          <q-input class="col-4" v-model="form.office_extension" label="Ext." outlined dense :disable="saving" />
        </div>
        <q-input v-model="form.company_email" label="Courriel (entreprise)" outlined dense :disable="saving" />
        <q-input v-model="form.user_id" label="Compte de connexion lié (user_id)" outlined dense :disable="saving"
          hint="Courriel du compte SSO/ERPNext — établit le lien session ↔ employé">
          <template #prepend><q-icon name="link" /></template>
        </q-input>
      </q-card-section>

      <q-card-actions align="right" class="q-pb-md q-pr-md" v-if="!loading">
        <q-btn flat label="Annuler" v-close-popup :disable="saving" />
        <q-btn v-if="mode === 'link'" unelevated color="primary" label="Lier" icon="link"
          :loading="saving" :disable="!linkTarget" @click="doLink" />
        <q-btn v-else unelevated color="primary" label="Enregistrer" icon="save" :loading="saving" @click="save" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Notify } from 'quasar'
import { listDocs, getDoc, updateDoc } from 'src/api/erp'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  // Éditer un employé précis (nom du doc ERPNext). Prioritaire sur linkEmail.
  employeeName: { type: String, default: '' },
  // Lier : courriel du compte sans employé (mode recherche/sélection).
  linkEmail: { type: String, default: '' },
})
const emit = defineEmits(['update:modelValue', 'saved'])
const open = computed({ get: () => props.modelValue, set: v => emit('update:modelValue', v) })

const loading = ref(false)
const saving = ref(false)
const mode = computed(() => props.employeeName ? 'edit' : 'link')

const EDITABLE = ['employee_name', 'designation', 'department', 'cell_number', 'office_extension', 'company_email', 'user_id']
const form = reactive({ employee_name: '', designation: null, department: null, cell_number: '', office_extension: '', company_email: '', user_id: '' })
const original = reactive({})

// Options Link (Designation/Department) chargées à l'ouverture, filtrables localement.
const allDesignations = ref([]), allDepartments = ref([])
const designationOpts = ref([]), departmentOpts = ref([])
function filterDesignations (val, update) { update(() => { const n = (val || '').toLowerCase(); designationOpts.value = allDesignations.value.filter(o => o.label.toLowerCase().includes(n)) }) }
function filterDepartments (val, update) { update(() => { const n = (val || '').toLowerCase(); departmentOpts.value = allDepartments.value.filter(o => o.label.toLowerCase().includes(n)) }) }

// Mode lien : recherche d'employés.
const linkTarget = ref(null)
const empOptions = ref([])
const empSearching = ref(false)
function filterEmployees (val, update) {
  const q = (val || '').trim()
  update(async () => {
    empSearching.value = true
    try {
      empOptions.value = await listDocs('Employee', {
        filters: { status: 'Active' },
        or_filters: q ? [['employee_name', 'like', '%' + q + '%'], ['name', 'like', '%' + q + '%']] : undefined,
        fields: ['name', 'employee_name', 'user_id'], limit: 15, orderBy: 'employee_name asc',
      })
    } catch { empOptions.value = [] } finally { empSearching.value = false }
  })
}

async function onShow () {
  linkTarget.value = null
  if (mode.value === 'edit') {
    loading.value = true
    try {
      const [doc, desigs, depts] = await Promise.all([
        getDoc('Employee', props.employeeName),
        listDocs('Designation', { fields: ['name'], limit: 200, orderBy: 'name asc' }),
        listDocs('Department', { fields: ['name'], limit: 200, orderBy: 'name asc' }),
      ])
      allDesignations.value = desigs.map(d => ({ label: d.name, value: d.name }))
      allDepartments.value = depts.map(d => ({ label: d.name, value: d.name }))
      designationOpts.value = allDesignations.value; departmentOpts.value = allDepartments.value
      for (const k of EDITABLE) { form[k] = doc[k] ?? (k === 'designation' || k === 'department' ? null : ''); original[k] = form[k] }
    } catch (e) {
      Notify.create({ type: 'negative', message: 'Chargement employé échoué: ' + e.message })
      open.value = false
    } finally { loading.value = false }
  }
}

async function save () {
  const changed = {}
  for (const k of EDITABLE) if ((form[k] ?? '') !== (original[k] ?? '')) changed[k] = form[k] || ''
  if (!Object.keys(changed).length) { open.value = false; return }
  saving.value = true
  try {
    await updateDoc('Employee', props.employeeName, changed)
    Notify.create({ type: 'positive', message: 'Profil employé mis à jour', timeout: 1500 })
    emit('saved', { name: props.employeeName, ...changed })
    open.value = false
  } catch (e) {
    Notify.create({ type: 'negative', message: 'Sauvegarde échouée: ' + e.message })
  } finally { saving.value = false }
}

async function doLink () {
  if (!linkTarget.value) return
  saving.value = true
  try {
    await updateDoc('Employee', linkTarget.value.name, { user_id: props.linkEmail })
    Notify.create({ type: 'positive', message: `${linkTarget.value.employee_name} lié à ${props.linkEmail}`, timeout: 2000 })
    emit('saved', { name: linkTarget.value.name, user_id: props.linkEmail, linked: true })
    open.value = false
  } catch (e) {
    Notify.create({ type: 'negative', message: 'Liaison échouée: ' + e.message })
  } finally { saving.value = false }
}
</script>
