<template>
  <q-dialog v-model="open">
    <q-card style="min-width:360px;max-width:440px">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">Mon profil</div>
        <q-space />
        <q-btn flat round dense icon="close" v-close-popup />
      </q-card-section>

      <q-card-section class="column items-center q-pt-md">
        <!-- Photo actuelle (grande) -->
        <UserAvatar :email="email" :name="nameDraft || name" :size="96" class="q-mb-sm" />
        <input ref="fileInput" type="file" accept="image/png,image/jpeg,image/webp,image/gif"
          class="hidden" @change="onFile">
        <div class="row q-gutter-sm q-mb-md">
          <q-btn dense no-caps unelevated color="primary" icon="photo_camera"
            :loading="uploading" label="Changer la photo" @click="pickFile" />
          <q-btn dense no-caps flat color="grey-7" icon="delete" label="Retirer"
            :disable="uploading" @click="removePhoto" />
        </div>

        <!-- Nom complet éditable -->
        <q-input v-model="nameDraft" label="Nom complet" outlined dense class="full-width q-mb-sm"
          :disable="savingName" @keyup.enter="commitName">
          <template #append>
            <q-btn v-if="nameDraft.trim() && nameDraft.trim() !== name" flat dense round
              icon="check" color="primary" :loading="savingName" @click="commitName">
              <q-tooltip>Enregistrer le nom</q-tooltip>
            </q-btn>
          </template>
        </q-input>

        <div class="full-width text-caption text-grey-6 q-mb-xs">{{ email }}</div>
        <div v-if="groups.length" class="row q-gutter-xs full-width q-mb-sm">
          <q-badge v-for="g in groups" :key="g" color="green-1" text-color="green-8">{{ g }}</q-badge>
        </div>

        <!-- Profil employé lié (lecture seule ici ; édition dans Équipe/Administration) -->
        <div class="full-width q-pa-sm q-mt-xs" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px">
          <div v-if="employee" class="row items-center no-wrap">
            <q-icon name="badge" size="18px" color="green-7" class="q-mr-sm" />
            <div class="col">
              <div class="text-body2">{{ employee.employee_name }}</div>
              <div class="text-caption text-grey-6">{{ [employee.designation, employee.department].filter(Boolean).join(' · ') || 'Profil employé lié' }}</div>
            </div>
          </div>
          <div v-else class="text-caption text-grey-6">
            <q-icon name="link_off" size="14px" /> Aucun profil employé lié à votre compte — un administrateur peut le lier (Équipe / Administration).
          </div>
        </div>
        <div class="text-caption text-grey-5 q-mt-md">
          La photo (ou vos initiales) apparaît partout où votre nom est affiché : fils de discussion, lecteurs, équipe.
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Notify } from 'quasar'
import UserAvatar from './UserAvatar.vue'
import { usePermissions } from 'src/composables/usePermissions'
import { useAvatar } from 'src/composables/useAvatar'

const props = defineProps({ modelValue: { type: Boolean, default: false } })
const emit = defineEmits(['update:modelValue'])
const open = computed({ get: () => props.modelValue, set: v => emit('update:modelValue', v) })

const { userEmail, userName, permissions, HUB_URL } = usePermissions()
const { uploadAvatar, deleteAvatar, fileToAvatarDataUrl } = useAvatar()

const email = computed(() => userEmail.value)
const name = computed(() => userName.value)
const groups = computed(() => permissions.value?.groups || [])
const employee = computed(() => permissions.value?.employee || null)

const fileInput = ref(null)
const uploading = ref(false)
const savingName = ref(false)
const nameDraft = ref('')

// (Ré)initialise le brouillon de nom à l'ouverture.
watch(open, (v) => { if (v) nameDraft.value = name.value || '' })

function pickFile () { fileInput.value?.click() }

async function onFile (e) {
  const file = e.target.files && e.target.files[0]
  e.target.value = '' // permet de re-choisir le même fichier
  if (!file) return
  uploading.value = true
  try {
    const dataUrl = await fileToAvatarDataUrl(file)
    await uploadAvatar(dataUrl)
  } catch (err) {
    Notify.create({ type: 'negative', message: 'Image illisible: ' + err.message })
  } finally {
    uploading.value = false
  }
}

async function removePhoto () {
  uploading.value = true
  try { await deleteAvatar() } finally { uploading.value = false }
}

async function commitName () {
  const n = nameDraft.value.trim()
  if (!n || n === name.value) return
  savingName.value = true
  try {
    const r = await fetch(HUB_URL + '/auth/users/' + encodeURIComponent(email.value) + '/name', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: n }),
    })
    const data = await r.json().catch(() => ({}))
    if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status))
    if (permissions.value) permissions.value.name = n // reflète immédiatement dans l'app
    Notify.create({ type: 'positive', message: 'Nom mis à jour', timeout: 1500 })
  } catch (err) {
    Notify.create({ type: 'negative', message: 'Erreur: ' + err.message })
  } finally {
    savingName.value = false
  }
}
</script>
