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

/**
 * Modal "Rejoindre le projet".
 *
 * Stratégie V1 (sans auth user) :
 *  - Si admin connecté : POST /api/members (créé un membre "person") puis
 *    POST /api/projects/:slug/members pour l'attacher.
 *  - Sinon : affiche un avertissement + lien vers /admin/login. On ne fait
 *    pas de fake-auth ni de bypass du token.
 *
 * V2 prévue : auth OIDC Nextcloud -> l'utilisateur se rejoint lui-même
 * via un endpoint public dédié.
 */

const props = defineProps<{ projectSlug: string }>()
const emit = defineEmits<{
  (e: 'close'): void
  (e: 'joined', payload: { member: Member; role: string }): void
}>()

const { isAuthenticated } = useAuth()
const name = ref('')
const email = ref('')
const submitting = ref(false)
const error = ref<string | null>(null)
const fieldErrors = ref<Record<string, string>>({})

async function submit() {
  error.value = null
  fieldErrors.value = {}
  if (!isAuthenticated.value) return
  if (!name.value.trim()) {
    fieldErrors.value.name = 'required'
    return
  }

  submitting.value = true
  try {
    // 1) Crée le membre (idempotent côté slug : si collision, suffixe -2 etc.).
    const member = await api.post<Member>('/api/members', {
      display_name: name.value.trim(),
      kind: 'person',
      contact_email: email.value.trim() || undefined,
    })
    // 2) L'attache au projet en rôle contributor.
    await api.post<{ project_id: number; role: string }>(
      `/api/projects/${encodeURIComponent(props.projectSlug)}/members`,
      { member_slug: member.slug, role: 'contributor' },
    )
    emit('joined', { member, role: 'contributor' })
    emit('close')
  } catch (e) {
    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 {
        error.value = e.payload.message ?? e.code
      }
    } else {
      error.value = 'Erreur réseau'
    }
  } finally {
    submitting.value = false
  }
}
</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">Rejoindre le projet</h2>
          <p class="text-sm text-donut-muted mt-1">Indique ton nom — tu seras ajouté en tant que contributeur.</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 + lien login. -->
      <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>
        — la V2 ouvrira l'auto-rejoint via Nextcloud.
      </div>

      <!-- Form admin -->
      <form v-else @submit.prevent="submit" class="space-y-3">
        <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 || fieldErrors.name ? 'border-red-400' : ''"
          />
          <p v-if="fieldErrors.display_name || fieldErrors.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>

        <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"
            class="text-sm px-4 py-2 rounded-lg bg-donut-text text-white hover:bg-black disabled:opacity-50"
          >
            {{ submitting ? 'Ajout…' : 'Rejoindre' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>
