<script setup lang="ts">
const route = useRoute()
const mandates = useMandatesStore()
const { $api } = useApi()

const mandateId = computed(() => route.params.id as string)

onMounted(async () => {
  await mandates.fetchById(mandateId.value)
})

onUnmounted(() => {
  mandates.clearCurrent()
})

watch(mandateId, async (newId) => {
  if (newId) await mandates.fetchById(newId)
})

// --- Helpers ---

const typeLabel = (t: string) => ({ statutory: 'Statutaire', functional: 'Fonctionnel' }[t] ?? t)

function formatDate(d: string | null): string {
  if (!d) return '-'
  return new Date(d).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', year: 'numeric' })
}

const terminalStatuses = ['completed', 'revoked']
const isTerminal = computed(() => !mandates.current || terminalStatuses.includes(mandates.current.status))
const canRevoke = computed(() => mandates.current?.status === 'active')
const isDraft = computed(() => mandates.current?.status === 'draft')

// --- Advance ---

const advancing = ref(false)

async function handleAdvance() {
  advancing.value = true
  try { await mandates.advance(mandateId.value) } catch { /* store holds error */ } finally { advancing.value = false }
}

// --- Identity search (shared for assign + edit) ---

interface IdentityResult { id: string; address: string; display_name: string | null }

function useIdentitySearch() {
  const query = ref('')
  const results = ref<IdentityResult[]>([])
  const searching = ref(false)
  const selectedId = ref<string | null>(null)
  const selectedLabel = ref('')
  let timer: ReturnType<typeof setTimeout> | null = null

  async function search(q: string) {
    if (q.length < 2) { results.value = []; return }
    searching.value = true
    try {
      results.value = await $api<IdentityResult[]>('/auth/identities', { query: { q } })
    } catch { results.value = [] } finally { searching.value = false }
  }

  function onInput(q: string) {
    query.value = q
    selectedId.value = null
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => search(q), 300)
  }

  function select(i: IdentityResult) {
    selectedId.value = i.id
    selectedLabel.value = i.display_name || i.address
    query.value = i.display_name || i.address
    results.value = []
  }

  function reset() {
    query.value = ''
    results.value = []
    selectedId.value = null
    selectedLabel.value = ''
  }

  return { query, results, searching, selectedId, selectedLabel, onInput, select, reset }
}

// --- Assign mandatee ---

const showAssignModal = ref(false)
const assigning = ref(false)
const assignSearch = useIdentitySearch()

async function handleAssign() {
  if (!assignSearch.selectedId.value) return
  assigning.value = true
  try {
    await mandates.assignMandatee(mandateId.value, assignSearch.selectedId.value)
    showAssignModal.value = false
    assignSearch.reset()
  } catch { /* store holds error */ } finally { assigning.value = false }
}

function openAssign() {
  assignSearch.reset()
  showAssignModal.value = true
}

// --- Revoke ---

const showRevokeConfirm = ref(false)
const revoking = ref(false)

async function handleRevoke() {
  revoking.value = true
  try {
    await mandates.revoke(mandateId.value)
    showRevokeConfirm.value = false
  } catch { /* store holds error */ } finally { revoking.value = false }
}

// --- Edit ---

const showEditModal = ref(false)
const editData = ref({ title: '', origin_id: null as string | null, description: '' })
const editOriginSearch = useIdentitySearch()
const saving = ref(false)

function openEdit() {
  if (!mandates.current) return
  editData.value = {
    title: mandates.current.title,
    origin_id: mandates.current.origin_id,
    description: mandates.current.description ?? '',
  }
  if (mandates.current.origin_display_name) {
    editOriginSearch.query.value = mandates.current.origin_display_name
    editOriginSearch.selectedId.value = mandates.current.origin_id
  } else {
    editOriginSearch.reset()
  }
  showEditModal.value = true
}

async function saveEdit() {
  saving.value = true
  try {
    await mandates.update(mandateId.value, {
      title: editData.value.title,
      origin_id: editOriginSearch.selectedId.value ?? editData.value.origin_id,
      description: editData.value.description || null,
    })
    showEditModal.value = false
  } catch { /* store holds error */ } finally { saving.value = false }
}

// --- Delete ---

const showDeleteConfirm = ref(false)
const deleting = ref(false)

async function handleDelete() {
  deleting.value = true
  try {
    await mandates.delete(mandateId.value)
    navigateTo('/mandates')
  } catch { /* store holds error */ } finally { deleting.value = false; showDeleteConfirm.value = false }
}
</script>

<template>
  <div class="space-y-6">
    <div>
      <UButton to="/mandates" variant="ghost" color="neutral" icon="i-lucide-arrow-left" label="Retour aux mandats" size="sm" />
    </div>

    <template v-if="mandates.loading">
      <div class="space-y-4">
        <USkeleton class="h-8 w-96" />
        <USkeleton class="h-4 w-64" />
        <div class="space-y-3 mt-8">
          <USkeleton v-for="i in 4" :key="i" class="h-20 w-full" />
        </div>
      </div>
    </template>

    <template v-else-if="mandates.error">
      <UCard>
        <div class="flex items-center gap-3 text-red-500">
          <UIcon name="i-lucide-alert-circle" class="text-xl" />
          <p>{{ mandates.error }}</p>
        </div>
      </UCard>
    </template>

    <template v-else-if="mandates.current">
      <!-- Header -->
      <div class="flex items-start justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">{{ mandates.current.title }}</h1>
          <div class="flex items-center gap-3 mt-2">
            <UBadge variant="subtle" color="primary">{{ typeLabel(mandates.current.mandate_type) }}</UBadge>
            <StatusBadge :status="mandates.current.status" type="mandate" />
          </div>
        </div>

        <div class="flex items-center gap-2">
          <UButton v-if="!isTerminal" icon="i-lucide-fast-forward" label="Avancer" color="primary" variant="soft" size="sm" :loading="advancing" @click="handleAdvance" />
          <UButton v-if="!isTerminal && !mandates.current.mandatee_id" icon="i-lucide-user-plus" label="Assigner un mandataire" variant="soft" color="primary" size="sm" @click="openAssign" />
          <UButton icon="i-lucide-pen-line" label="Modifier" variant="soft" color="neutral" size="sm" @click="openEdit" />
          <UButton v-if="canRevoke" icon="i-lucide-shield-off" label="Revoquer" variant="soft" color="error" size="sm" @click="showRevokeConfirm = true" />
          <UButton v-if="isDraft" icon="i-lucide-trash-2" label="Supprimer" variant="soft" color="error" size="sm" @click="showDeleteConfirm = true" />
        </div>
      </div>

      <!-- Error feedback -->
      <div v-if="mandates.error" class="text-sm text-red-500 bg-red-50 dark:bg-red-950 px-4 py-2 rounded-lg">
        {{ mandates.error }}
      </div>

      <UCard v-if="mandates.current.description">
        <div>
          <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-1">Description</h3>
          <p class="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap">{{ mandates.current.description }}</p>
        </div>
      </UCard>

      <!-- Metadata -->
      <UCard>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div>
            <p class="text-gray-500">Mandataire</p>
            <p class="font-medium text-gray-900 dark:text-white">
              <template v-if="mandates.current.mandatee_display_name">{{ mandates.current.mandatee_display_name }}</template>
              <template v-else-if="mandates.current.mandatee_id"><span class="font-mono text-xs">{{ mandates.current.mandatee_id.slice(0, 12) }}…</span></template>
              <template v-else><span class="text-gray-400 italic">Non assigne</span></template>
            </p>
          </div>
          <div>
            <p class="text-gray-500">Origine</p>
            <p class="font-medium text-gray-900 dark:text-white">
              <template v-if="mandates.current.origin_display_name">{{ mandates.current.origin_display_name }}</template>
              <template v-else><span class="text-gray-400 italic">Non renseigné</span></template>
            </p>
          </div>
          <div>
            <p class="text-gray-500">Debut</p>
            <p class="font-medium text-gray-900 dark:text-white">{{ formatDate(mandates.current.starts_at) }}</p>
          </div>
          <div>
            <p class="text-gray-500">Fin</p>
            <p class="font-medium text-gray-900 dark:text-white">{{ formatDate(mandates.current.ends_at) }}</p>
          </div>
        </div>
      </UCard>

      <UCard>
        <div class="grid grid-cols-2 gap-4 text-sm">
          <div>
            <p class="text-gray-500">Cree le</p>
            <p class="font-medium text-gray-900 dark:text-white">{{ formatDate(mandates.current.created_at) }}</p>
          </div>
          <div>
            <p class="text-gray-500">Mis a jour le</p>
            <p class="font-medium text-gray-900 dark:text-white">{{ formatDate(mandates.current.updated_at) }}</p>
          </div>
        </div>
      </UCard>

      <!-- Steps -->
      <div>
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Etapes du mandat</h2>
        <MandateTimeline :steps="mandates.current.steps" :current-status="mandates.current.status" />
      </div>
    </template>

    <!-- Modal : Assigner un mandataire -->
    <UModal v-model:open="showAssignModal">
      <template #content>
        <div class="p-6 space-y-4">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Assigner un mandataire</h3>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Rechercher un membre <span class="text-red-500">*</span>
            </label>
            <div class="relative">
              <input
                :value="assignSearch.query.value"
                type="text"
                class="w-full rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                placeholder="Nom ou adresse Duniter…"
                @input="assignSearch.onInput(($event.target as HTMLInputElement).value)"
              />
              <div
                v-if="assignSearch.results.value.length"
                class="absolute z-10 mt-1 w-full bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 shadow-lg overflow-hidden"
              >
                <button
                  v-for="r in assignSearch.results.value"
                  :key="r.id"
                  class="w-full flex items-center gap-3 px-4 py-2 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-800"
                  @click="assignSearch.select(r)"
                >
                  <UIcon name="i-lucide-user" class="text-gray-400 shrink-0" />
                  <div>
                    <p class="font-medium text-gray-900 dark:text-white">{{ r.display_name || r.address }}</p>
                    <p class="text-xs text-gray-500 font-mono">{{ r.address.slice(0, 20) }}…</p>
                  </div>
                </button>
              </div>
            </div>
            <p v-if="assignSearch.selectedId.value" class="text-xs text-green-600 flex items-center gap-1">
              <UIcon name="i-lucide-check-circle" /> {{ assignSearch.selectedLabel.value }} sélectionné
            </p>
          </div>

          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button class="px-4 py-2 text-sm text-gray-600 hover:text-gray-900" @click="showAssignModal = false">Annuler</button>
            <button
              class="px-4 py-2 text-sm font-medium bg-primary-600 text-white rounded-xl hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              :disabled="!assignSearch.selectedId.value || assigning"
              @click="handleAssign"
            >
              <UIcon v-if="assigning" name="i-lucide-loader-2" class="animate-spin text-sm" />
              Assigner
            </button>
          </div>
        </div>
      </template>
    </UModal>

    <!-- Modal : Révoquer -->
    <UModal v-model:open="showRevokeConfirm">
      <template #content>
        <div class="p-6 space-y-4">
          <h3 class="text-lg font-semibold text-red-600">Confirmer la revocation</h3>
          <p class="text-sm text-gray-600 dark:text-gray-400">
            Etes-vous sur de vouloir revoquer ce mandat ? Le mandataire perdra ses droits et responsabilites.
          </p>
          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button class="px-4 py-2 text-sm text-gray-600 hover:text-gray-900" @click="showRevokeConfirm = false">Annuler</button>
            <button
              class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-xl hover:bg-red-700 flex items-center gap-2"
              :disabled="revoking"
              @click="handleRevoke"
            >
              <UIcon v-if="revoking" name="i-lucide-loader-2" class="animate-spin text-sm" />
              Revoquer
            </button>
          </div>
        </div>
      </template>
    </UModal>

    <!-- Modal : Modifier -->
    <UModal v-model:open="showEditModal">
      <template #content>
        <div class="p-6 space-y-4">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Modifier le mandat</h3>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Titre</label>
            <input v-model="editData.title" type="text" class="w-full rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500" />
          </div>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Origine</label>
            <div class="relative">
              <input
                :value="editOriginSearch.query.value"
                type="text"
                class="w-full rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                placeholder="Rechercher un membre…"
                @input="editOriginSearch.onInput(($event.target as HTMLInputElement).value)"
              />
              <div
                v-if="editOriginSearch.results.value.length"
                class="absolute z-10 mt-1 w-full bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 shadow-lg overflow-hidden"
              >
                <button
                  v-for="r in editOriginSearch.results.value"
                  :key="r.id"
                  class="w-full flex items-center gap-3 px-4 py-2 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-800"
                  @click="editOriginSearch.select(r)"
                >
                  <UIcon name="i-lucide-user" class="text-gray-400 shrink-0" />
                  <span>{{ r.display_name || r.address }}</span>
                </button>
              </div>
            </div>
          </div>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Description</label>
            <textarea v-model="editData.description" rows="4" class="w-full rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none" />
          </div>

          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button class="px-4 py-2 text-sm text-gray-600 hover:text-gray-900" @click="showEditModal = false">Annuler</button>
            <button
              class="px-4 py-2 text-sm font-medium bg-primary-600 text-white rounded-xl hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              :disabled="!editData.title?.trim() || saving"
              @click="saveEdit"
            >
              <UIcon v-if="saving" name="i-lucide-loader-2" class="animate-spin text-sm" />
              Enregistrer
            </button>
          </div>
        </div>
      </template>
    </UModal>

    <!-- Modal : Supprimer -->
    <UModal v-model:open="showDeleteConfirm">
      <template #content>
        <div class="p-6 space-y-4">
          <h3 class="text-lg font-semibold text-red-600">Confirmer la suppression</h3>
          <p class="text-sm text-gray-600 dark:text-gray-400">
            Etes-vous sur de vouloir supprimer ce mandat ? Cette action est irreversible.
          </p>
          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button class="px-4 py-2 text-sm text-gray-600 hover:text-gray-900" @click="showDeleteConfirm = false">Annuler</button>
            <button
              class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-xl hover:bg-red-700 flex items-center gap-2"
              :disabled="deleting"
              @click="handleDelete"
            >
              <UIcon v-if="deleting" name="i-lucide-loader-2" class="animate-spin text-sm" />
              Supprimer
            </button>
          </div>
        </div>
      </template>
    </UModal>
  </div>
</template>
