<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { api, ApiError } from '@/api/client'
import { useAuth } from '@/composables/useAuth'
import type { Category, ProjectDetail, Wrapped } from '@/types/api'
import LoadingState from '@/components/LoadingState.vue'

const router = useRouter()
const { isAuthenticated } = useAuth()

const categories = ref<Category[]>([])
const loadingCategories = ref(true)

const form = ref({
  title: '',
  category_id: '' as string | number,
  territory: 'Marseille',
  short_description: '',
  context_description: '',
  objectives: '',
  cover_image_url: '',
})
const submitting = ref(false)
const fieldErrors = ref<Record<string, string>>({})
const generalError = ref<string | null>(null)

onMounted(async () => {
  try {
    const r = await api.get<Wrapped<Category>>('/api/categories')
    categories.value = r.data
  } finally {
    loadingCategories.value = false
  }
})

const canSubmit = computed(() => isAuthenticated.value && form.value.title.trim() && form.value.category_id)

async function submit() {
  fieldErrors.value = {}
  generalError.value = null
  if (!isAuthenticated.value) {
    generalError.value = "Tu dois être connecté en admin pour créer un projet."
    return
  }
  submitting.value = true
  try {
    const body: Record<string, unknown> = {
      title: form.value.title.trim(),
      category_id: Number(form.value.category_id),
    }
    if (form.value.territory.trim()) body.territory = form.value.territory.trim()
    if (form.value.short_description.trim()) body.short_description = form.value.short_description.trim()
    if (form.value.context_description.trim()) body.context_description = form.value.context_description.trim()
    if (form.value.objectives.trim()) body.objectives = form.value.objectives.trim()
    if (form.value.cover_image_url.trim()) body.cover_image_url = form.value.cover_image_url.trim()

    const created = await api.post<ProjectDetail>('/api/projects', body)
    router.push({ name: 'project-detail', params: { slug: created.slug } })
  } catch (e) {
    if (e instanceof ApiError) {
      if (e.status === 422) {
        fieldErrors.value = e.fields
      } else if (e.status === 401) {
        generalError.value = 'Token admin invalide ou expiré.'
      } else {
        generalError.value = e.payload.message ?? e.code
      }
    } else {
      generalError.value = 'Erreur réseau'
    }
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="px-10 py-8 max-w-3xl">
    <RouterLink
      :to="{ name: 'projects' }"
      class="inline-flex items-center gap-1.5 text-sm text-donut-muted hover:text-donut-text"
    >
      <svg viewBox="0 0 24 24" class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="m12 19-7-7 7-7M5 12h14"/>
      </svg>
      Retour aux projets
    </RouterLink>

    <header class="mt-4">
      <h1 class="text-3xl font-semibold text-donut-text">Nouveau Projet</h1>
      <p class="text-donut-muted mt-1">Proposez une nouvelle initiative citoyenne pour la communauté.</p>
    </header>

    <!-- Avertissement si pas connecté admin -->
    <div
      v-if="!isAuthenticated"
      class="mt-6 rounded-lg border border-amber-200 bg-amber-50 text-amber-800 px-4 py-3 text-sm"
    >
      La création de projets est réservée à l'admin en V1.
      <RouterLink :to="{ name: 'admin-login' }" class="underline font-medium">Se connecter</RouterLink>
      pour publier.
    </div>

    <form
      @submit.prevent="submit"
      class="mt-6 rounded-xl border border-donut-border bg-donut-surface p-6 space-y-5"
    >
      <header class="border-b border-donut-border pb-4">
        <h2 class="text-base font-semibold text-donut-text">Détails du projet</h2>
        <p class="text-sm text-donut-muted mt-0.5">Décrivez clairement votre projet pour encourager la participation.</p>
      </header>

      <!-- Titre -->
      <div>
        <label class="block text-sm font-medium text-donut-text mb-1">Titre du projet *</label>
        <input
          v-model="form.title"
          type="text"
          placeholder="Ex: Cartographie des îlots de chaleur"
          class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text"
          :class="fieldErrors.title ? 'border-red-400' : ''"
        />
        <p v-if="fieldErrors.title" class="text-xs text-red-600 mt-1">Titre requis.</p>
      </div>

      <!-- Catégorie + Territoire -->
      <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium text-donut-text mb-1">Catégorie thématique *</label>
          <LoadingState v-if="loadingCategories" />
          <select
            v-else
            v-model="form.category_id"
            class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text"
            :class="fieldErrors.category_id ? 'border-red-400' : ''"
          >
            <option value="" disabled>Sélectionner une catégorie</option>
            <option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</option>
          </select>
          <p v-if="fieldErrors.category_id" class="text-xs text-red-600 mt-1">
            {{ fieldErrors.category_id === 'not_found' ? 'Catégorie introuvable.' : 'Catégorie requise.' }}
          </p>
        </div>
        <div>
          <label class="block text-sm font-medium text-donut-text mb-1">Territoire / Quartier</label>
          <input
            v-model="form.territory"
            type="text"
            class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text"
          />
        </div>
      </div>

      <!-- Description courte -->
      <div>
        <label class="block text-sm font-medium text-donut-text mb-1">Description courte</label>
        <textarea
          v-model="form.short_description"
          rows="2"
          placeholder="Un résumé en une ou deux phrases (utilisé sur les cartes)."
          class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text resize-y"
        />
      </div>

      <!-- Contexte -->
      <div>
        <label class="block text-sm font-medium text-donut-text mb-1">Description complète</label>
        <textarea
          v-model="form.context_description"
          rows="5"
          placeholder="Présentez le contexte et les enjeux…"
          class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text resize-y"
        />
      </div>

      <!-- Objectifs -->
      <div>
        <label class="block text-sm font-medium text-donut-text mb-1">Objectifs et impacts attendus</label>
        <textarea
          v-model="form.objectives"
          rows="3"
          placeholder="Quels sont les résultats concrets visés ?"
          class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text resize-y"
        />
      </div>

      <!-- Image cover -->
      <div>
        <label class="block text-sm font-medium text-donut-text mb-1">Image de couverture (URL)</label>
        <input
          v-model="form.cover_image_url"
          type="url"
          placeholder="https://…"
          class="w-full bg-white border border-donut-border rounded-lg px-3 py-2.5 text-sm outline-none focus:border-donut-text"
          :class="fieldErrors.cover_image_url ? 'border-red-400' : ''"
        />
        <p class="text-xs text-donut-muted mt-1">Optionnel — une image d'illustration pour votre projet.</p>
      </div>

      <!-- Erreur générale -->
      <div v-if="generalError" class="rounded-lg border border-red-200 bg-red-50 text-red-700 px-3 py-2 text-sm">
        {{ generalError }}
      </div>

      <!-- Actions -->
      <div class="flex items-center justify-end gap-2 pt-2 border-t border-donut-border">
        <RouterLink
          :to="{ name: 'projects' }"
          class="px-4 py-2 rounded-lg text-sm font-medium border border-donut-border hover:bg-gray-50"
        >
          Annuler
        </RouterLink>
        <button
          type="submit"
          :disabled="!canSubmit || submitting"
          class="px-4 py-2 rounded-lg bg-donut-text text-white text-sm font-medium hover:bg-black disabled:opacity-50"
        >
          {{ submitting ? 'Publication…' : 'Publier le projet' }}
        </button>
      </div>
    </form>
  </section>
</template>
