<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import { api, ApiError } from '@/api/client'
import { useAuth } from '@/composables/useAuth'
import type { Member, MemberRole, Paginated } from '@/types/api'
import Avatar from './Avatar.vue'

/**
 * Modal "Rejoindre le projet" — 2 modes :
 *   - Membre existant : on choisit dans l'annuaire (exclut ceux déjà sur l'équipe)
 *     + rôle. POST direct sur project_members.
 *   - Nouveau membre  : on saisit nom + email, on crée le membre dans l'annuaire
 *     puis on l'attache au projet. POST members + POST project_members.
 *
 * V1 = token admin requis pour les 2 modes (cf. spec API).
 */

const props = defineProps<{
  projectSlug: string
  /** Slugs des membres déjà sur l'équipe — pour les masquer de la liste "existant". */
  excludeSlugs: string[]
}>()
const emit = defineEmits<{
  (e: 'close'): void
  (e: 'joined', payload: { member: Member; role: MemberRole }): void
}>()

const { isAuthenticated } = useAuth()

type Mode = 'existing' | 'new'
const mode = ref<Mode>('existing')
const role = ref<MemberRole>('contributor')

// --- Mode "existing" ---
const directory = ref<Member[]>([])
const directoryLoading = ref(false)
const directoryError = ref<string | null>(null)
const directoryLoaded = ref(false)
const selectedSlug = ref('')

async function loadDirectory() {
  if (directoryLoaded.value || directoryLoading.value) return
  directoryLoading.value = true
  directoryError.value = null
  try {
    const r = await api.get<Paginated<Member>>('/api/members', { query: { per_page: 100 } })
    directory.value = r.data
    directoryLoaded.value = true
  } catch (e) {
    // Surfacer l'erreur : sans ça, l'utilisateur voit "tous les membres déjà
    // sur ce projet" alors que c'est en réalité l'API qui a échoué.
    directoryError.value = e instanceof ApiError
      ? (e.payload.message ?? e.code)
      : "Impossible de charger l'annuaire."
  } finally {
    directoryLoading.value = false
  }
}

// Lazy : on charge l'annuaire la première fois qu'on passe en mode "existing"
// (qui est aussi le mode par défaut). Évite un GET /api/members?per_page=100
// gratuit si l'admin clique direct sur "Nouveau membre".
function switchMode(next: Mode) {
  mode.value = next
  resetErrors()
  if (next === 'existing') loadDirectory()
}
onMounted(() => {
  if (isAuthenticated.value && mode.value === 'existing') loadDirectory()
})

const availableMembers = computed(() =>
  directory.value
    .filter(m => !props.excludeSlugs.includes(m.slug))
    .sort((a, b) => a.display_name.localeCompare(b.display_name, 'fr')),
)

const selectedMember = computed(() =>
  availableMembers.value.find(m => m.slug === selectedSlug.value) ?? null,
)

// --- Mode "new" ---
const name = ref('')
const email = ref('')

const submitting = ref(false)
const error = ref<string | null>(null)
const fieldErrors = ref<Record<string, string>>({})

function resetErrors() {
  error.value = null
  fieldErrors.value = {}
}

async function submitExisting() {
  resetErrors()
  if (!selectedSlug.value) {
    fieldErrors.value.member_slug = 'required'
    return
  }
  submitting.value = true
  try {
    await api.post(`/api/projects/${encodeURIComponent(props.projectSlug)}/members`, {
      member_slug: selectedSlug.value,
      role: role.value,
    })
    const member = directory.value.find(m => m.slug === selectedSlug.value)
    if (member) emit('joined', { member, role: role.value })
    emit('close')
  } catch (e) {
    handleError(e)
  } finally {
    submitting.value = false
  }
}

async function submitNew() {
  resetErrors()
  if (!name.value.trim()) {
    fieldErrors.value.display_name = 'required'
    return
  }
  submitting.value = true
  try {
    const member = await api.post<Member>('/api/members', {
      display_name: name.value.trim(),
      kind: 'person',
      contact_email: email.value.trim() || undefined,
    })
    await api.post(`/api/projects/${encodeURIComponent(props.projectSlug)}/members`, {
      member_slug: member.slug,
      role: role.value,
    })
    emit('joined', { member, role: role.value })
    emit('close')
  } catch (e) {
    handleError(e)
  } finally {
    submitting.value = false
  }
}

function handleError(e: unknown) {
  if (e instanceof ApiError) {
    if (e.status === 422) {
      fieldErrors.value = e.fields
    } else if (e.status === 409) {
      error.value = e.payload.message ?? 'Ce membre fait déjà partie du projet.'
    } else if (e.status === 401) {
      error.value = 'Session admin expirée. Reconnecte-toi.'
    } else {
      error.value = e.payload.message ?? e.code
    }
  } else {
    error.value = 'Erreur réseau'
  }
}

function submit() {
  if (mode.value === 'existing') submitExisting()
  else submitNew()
}
</script>

<template>
  <div
    class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
    @click.self="emit('close')"
  >
    <div class="bg-donut-surface rounded-2xl shadow-xl w-full max-w-md p-6">
      <div class="flex items-start justify-between gap-4 mb-4">
        <div>
          <h2 class="text-xl font-semibold text-donut-text">Ajouter à l'équipe</h2>
          <p class="text-sm text-donut-muted mt-1">Choisis un membre existant ou crées-en un nouveau.</p>
        </div>
        <button
          type="button"
          class="text-donut-muted hover:text-donut-text"
          @click="emit('close')"
          aria-label="Fermer"
        >
          <svg viewBox="0 0 24 24" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
            <path d="M18 6 6 18M6 6l12 12"/>
          </svg>
        </button>
      </div>

      <!-- Pas de token : avertissement -->
      <div v-if="!isAuthenticated" class="rounded-lg border border-amber-200 bg-amber-50 text-amber-800 px-4 py-3 text-sm">
        L'ajout de membres est réservé à l'admin en V1.
        <RouterLink :to="{ name: 'admin-login' }" class="underline font-medium ml-1">
          Se connecter
        </RouterLink>
      </div>

      <template v-else>
        <!-- Tabs mode -->
        <div class="flex items-center bg-gray-100 rounded-lg p-1 mb-4 text-sm">
          <button
            type="button"
            :class="[
              'flex-1 px-3 py-1.5 rounded-md transition-colors',
              mode === 'existing'
                ? 'bg-white shadow-sm font-medium text-donut-text'
                : 'text-donut-muted hover:text-donut-text',
            ]"
            @click="switchMode('existing')"
          >Membre existant</button>
          <button
            type="button"
            :class="[
              'flex-1 px-3 py-1.5 rounded-md transition-colors',
              mode === 'new'
                ? 'bg-white shadow-sm font-medium text-donut-text'
                : 'text-donut-muted hover:text-donut-text',
            ]"
            @click="switchMode('new')"
          >Nouveau membre</button>
        </div>

        <form @submit.prevent="submit" class="space-y-3">
          <!-- Mode existant : sélection dans annuaire -->
          <template v-if="mode === 'existing'">
            <div>
              <label class="block text-sm font-medium text-donut-text mb-1">Membre</label>
              <div v-if="directoryLoading" class="text-sm text-donut-muted">Chargement de l'annuaire…</div>
              <div
                v-else-if="directoryError"
                class="rounded-lg border border-red-200 bg-red-50 text-red-700 px-3 py-2 text-sm flex items-center justify-between gap-2"
              >
                <span>{{ directoryError }}</span>
                <button type="button" class="underline font-medium" @click="directoryLoaded = false; loadDirectory()">Réessayer</button>
              </div>
              <div v-else-if="availableMembers.length === 0" class="text-sm text-donut-muted">
                Tous les membres de l'annuaire sont déjà sur ce projet.
              </div>
              <select
                v-else
                v-model="selectedSlug"
                class="w-full bg-white border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text"
                :class="fieldErrors.member_slug ? 'border-red-400' : ''"
              >
                <option value="" disabled>Choisir un membre…</option>
                <option v-for="m in availableMembers" :key="m.id" :value="m.slug">
                  {{ m.display_name }} <template v-if="m.kind !== 'person'">— {{ m.kind === 'org' ? 'org' : 'collectif' }}</template>
                </option>
              </select>
              <!-- Aperçu visuel du membre sélectionné -->
              <div v-if="selectedMember" class="mt-2 flex items-center gap-2 text-sm text-donut-muted">
                <Avatar
                  :name="selectedMember.display_name"
                  :initials="selectedMember.initials"
                  :avatar-url="selectedMember.avatar_url"
                  :size="28"
                />
                <span class="truncate">{{ selectedMember.bio ?? 'Aucune bio renseignée.' }}</span>
              </div>
            </div>
          </template>

          <!-- Mode nouveau : création -->
          <template v-else>
            <div>
              <label class="block text-sm font-medium text-donut-text mb-1">Nom *</label>
              <input
                v-model="name"
                type="text"
                placeholder="ex: Camille D."
                class="w-full bg-white border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text"
                :class="fieldErrors.display_name ? 'border-red-400' : ''"
              />
              <p v-if="fieldErrors.display_name" class="text-xs text-red-600 mt-1">Le nom est requis.</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-donut-text mb-1">Email (optionnel)</label>
              <input
                v-model="email"
                type="email"
                placeholder="camille@example.org"
                class="w-full bg-white border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text"
                :class="fieldErrors.contact_email ? 'border-red-400' : ''"
              />
              <p v-if="fieldErrors.contact_email" class="text-xs text-red-600 mt-1">Email invalide.</p>
            </div>
          </template>

          <!-- Rôle (toujours visible) -->
          <div>
            <label class="block text-sm font-medium text-donut-text mb-1">Rôle dans le projet</label>
            <select
              v-model="role"
              class="w-full bg-white border border-donut-border rounded-lg px-3 py-2 text-sm outline-none focus:border-donut-text"
            >
              <option value="admin">Admin — peut tout modifier</option>
              <option value="contributor">Contributor — participe activement</option>
              <option value="observer">Observer — accès lecture / suivi</option>
            </select>
          </div>

          <div v-if="error" class="rounded-lg border border-red-200 bg-red-50 text-red-700 px-3 py-2 text-sm">
            {{ error }}
          </div>

          <div class="flex items-center justify-end gap-2 pt-2">
            <button
              type="button"
              class="text-sm px-3 py-2 rounded-lg hover:bg-gray-50 text-donut-text"
              @click="emit('close')"
            >Annuler</button>
            <button
              type="submit"
              :disabled="submitting || (mode === 'existing' && availableMembers.length === 0)"
              class="text-sm px-4 py-2 rounded-lg bg-donut-text text-white hover:bg-black disabled:opacity-50"
            >{{ submitting ? 'Ajout…' : 'Ajouter à l’équipe' }}</button>
          </div>
        </form>
      </template>
    </div>
  </div>
</template>
