<script setup lang="ts">
const route = useRoute()
const mandates = useMandatesStore()

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)
  }
})

// --- Status helpers ---

const typeLabel = (mandateType: string) => {
  switch (mandateType) {
    case 'techcomm': return 'Comite technique'
    case 'smith': return 'Forgeron'
    case 'custom': return 'Personnalise'
    default: return mandateType
  }
}

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

// --- Terminal state check ---

const terminalStatuses = ['completed', 'revoked']
const isTerminal = computed(() => {
  if (!mandates.current) return true
  return terminalStatuses.includes(mandates.current.status)
})

const canRevoke = computed(() => {
  if (!mandates.current) return false
  return mandates.current.status === 'active'
})

// --- Advance action ---

const advancing = ref(false)

async function handleAdvance() {
  advancing.value = true
  try {
    await mandates.advance(mandateId.value)
  } catch {
    // Error handled by store
  } finally {
    advancing.value = false
  }
}

// --- Assign mandatee ---

const showAssignModal = ref(false)
const mandateeAddress = ref('')
const assigning = ref(false)

async function handleAssign() {
  if (!mandateeAddress.value.trim()) return
  assigning.value = true
  try {
    await mandates.assignMandatee(mandateId.value, mandateeAddress.value.trim())
    showAssignModal.value = false
    mandateeAddress.value = ''
  } catch {
    // Error handled by store
  } finally {
    assigning.value = false
  }
}

// --- 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 {
    // Error handled by store
  } finally {
    revoking.value = false
  }
}

// --- Edit modal ---

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

function openEdit() {
  if (!mandates.current) return
  editData.value = {
    title: mandates.current.title,
    description: mandates.current.description,
  }
  showEditModal.value = true
}

async function saveEdit() {
  saving.value = true
  try {
    await mandates.update(mandateId.value, editData.value)
    showEditModal.value = false
  } catch {
    // Error handled by store
  } finally {
    saving.value = false
  }
}

// --- Delete ---

const showDeleteConfirm = ref(false)
const deleting = ref(false)
const isDraft = computed(() => mandates.current?.status === 'draft')

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

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

    <!-- Loading state -->
    <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>

    <!-- Error state -->
    <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>

    <!-- Mandate detail -->
    <template v-else-if="mandates.current">
      <!-- Header with actions -->
      <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>

        <!-- Action buttons -->
        <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="showAssignModal = true"
          />
          <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>

      <!-- Description -->
      <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_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">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>
            <p class="text-gray-500">Nombre d'etapes</p>
            <p class="font-medium text-gray-900 dark:text-white">
              {{ mandates.current.steps.length }}
            </p>
          </div>
        </div>
      </UCard>

      <!-- Dates metadata -->
      <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 timeline -->
      <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>

    <!-- Assign mandatee modal -->
    <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">
              Adresse du mandataire <span class="text-red-500">*</span>
            </label>
            <UInput
              v-model="mandateeAddress"
              placeholder="Adresse Duniter (ex: 5Grw...)
"
            />
            <p class="text-xs text-gray-500">
              Adresse SS58 du membre de la toile de confiance
            </p>
          </div>

          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <UButton
              label="Annuler"
              variant="ghost"
              color="neutral"
              @click="showAssignModal = false"
            />
            <UButton
              label="Assigner"
              icon="i-lucide-user-plus"
              color="primary"
              :loading="assigning"
              :disabled="!mandateeAddress.trim()"
              @click="handleAssign"
            />
          </div>
        </div>
      </template>
    </UModal>

    <!-- Revoke confirmation modal -->
    <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">
            <UButton
              label="Annuler"
              variant="ghost"
              color="neutral"
              @click="showRevokeConfirm = false"
            />
            <UButton
              label="Revoquer"
              icon="i-lucide-shield-off"
              color="error"
              :loading="revoking"
              @click="handleRevoke"
            />
          </div>
        </div>
      </template>
    </UModal>

    <!-- Edit modal -->
    <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>
            <UInput v-model="editData.title" />
          </div>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Description</label>
            <UTextarea v-model="editData.description" :rows="4" />
          </div>

          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <UButton
              label="Annuler"
              variant="ghost"
              color="neutral"
              @click="showEditModal = false"
            />
            <UButton
              label="Enregistrer"
              icon="i-lucide-save"
              color="primary"
              :loading="saving"
              :disabled="!editData.title?.trim()"
              @click="saveEdit"
            />
          </div>
        </div>
      </template>
    </UModal>

    <!-- Delete confirmation modal -->
    <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">
            <UButton
              label="Annuler"
              variant="ghost"
              color="neutral"
              @click="showDeleteConfirm = false"
            />
            <UButton
              label="Supprimer"
              icon="i-lucide-trash-2"
              color="error"
              :loading="deleting"
              @click="handleDelete"
            />
          </div>
        </div>
      </template>
    </UModal>
  </div>
</template>
