<script setup lang="ts">
import type { SanctuaryEntryOut } from '~/components/sanctuary/SanctuaryEntry.vue'

const { $api } = useApi()

const entries = ref<SanctuaryEntryOut[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

const filterType = ref<string | undefined>(undefined)

const typeOptions = [
  { label: 'Tous les types', value: undefined },
  { label: 'Document', value: 'document' },
  { label: 'Decision', value: 'decision' },
  { label: 'Resultat de vote', value: 'vote_result' },
]

// Verification state
const verifying = ref<string | null>(null)
const verifyResult = ref<{ id: string; match: boolean; message: string } | null>(null)

async function loadEntries() {
  loading.value = true
  error.value = null

  try {
    const query: Record<string, string> = {}
    if (filterType.value) query.entry_type = filterType.value

    entries.value = await $api<SanctuaryEntryOut[]>('/sanctuary/', { query })
  } catch (err: any) {
    error.value = err?.data?.detail || err?.message || 'Erreur lors du chargement des entrees'
  } finally {
    loading.value = false
  }
}

async function handleVerify(id: string) {
  verifying.value = id
  verifyResult.value = null

  try {
    const result = await $api<{ match: boolean; message: string }>(
      `/sanctuary/${id}/verify`,
    )
    verifyResult.value = { id, ...result }
  } catch (err: any) {
    verifyResult.value = {
      id,
      match: false,
      message: err?.data?.detail || err?.message || 'Erreur lors de la verification',
    }
  } finally {
    verifying.value = null
  }
}

onMounted(() => {
  loadEntries()
})

watch(filterType, () => {
  loadEntries()
})
</script>

<template>
  <div class="space-y-6">
    <!-- Header -->
    <div>
      <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
        Sanctuaire
      </h1>
      <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
        Archive immuable : documents et decisions ancres sur IPFS avec preuve on-chain via system.remark
      </p>
    </div>

    <!-- Filters -->
    <div class="flex flex-wrap gap-4">
      <USelect
        v-model="filterType"
        :items="typeOptions"
        placeholder="Type d'entree"
        class="w-56"
      />
    </div>

    <!-- Verification result banner -->
    <UCard v-if="verifyResult">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-3">
          <UIcon
            :name="verifyResult.match ? 'i-lucide-check-circle' : 'i-lucide-alert-triangle'"
            :class="verifyResult.match ? 'text-green-500 text-xl' : 'text-red-500 text-xl'"
          />
          <div>
            <p :class="verifyResult.match ? 'text-green-700 dark:text-green-400 font-medium' : 'text-red-700 dark:text-red-400 font-medium'">
              {{ verifyResult.match ? 'Integrite verifiee' : 'Verification echouee' }}
            </p>
            <p class="text-sm text-gray-500">{{ verifyResult.message }}</p>
          </div>
        </div>
        <UButton
          icon="i-lucide-x"
          variant="ghost"
          color="neutral"
          size="xs"
          @click="verifyResult = null"
        />
      </div>
    </UCard>

    <!-- Loading state -->
    <template v-if="loading">
      <div class="space-y-3">
        <USkeleton v-for="i in 4" :key="i" class="h-48 w-full" />
      </div>
    </template>

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

    <!-- Empty state -->
    <template v-else-if="entries.length === 0">
      <UCard>
        <div class="text-center py-8">
          <UIcon name="i-lucide-archive" class="text-4xl text-gray-400 mb-3" />
          <p class="text-gray-500">Aucune entree dans le sanctuaire pour le moment</p>
          <p class="text-xs text-gray-400 mt-1">
            Les documents et decisions adoptes seront automatiquement archives ici
          </p>
        </div>
      </UCard>
    </template>

    <!-- Entries list using SanctuaryEntry component -->
    <template v-else>
      <div class="space-y-4">
        <div v-for="entry in entries" :key="entry.id" class="relative">
          <SanctuaryEntry
            :entry="entry"
            @verify="handleVerify"
          />
          <!-- Loading overlay for verification -->
          <div
            v-if="verifying === entry.id"
            class="absolute inset-0 bg-white/50 dark:bg-gray-900/50 flex items-center justify-center rounded-lg"
          >
            <div class="flex items-center gap-2 text-sm text-gray-500">
              <UIcon name="i-lucide-loader-2" class="animate-spin" />
              <span>Verification en cours...</span>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- Info card -->
    <UCard>
      <div class="space-y-3">
        <div class="flex items-center gap-2">
          <UIcon name="i-lucide-info" class="text-primary" />
          <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300">
            Processus d'archivage
          </h3>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs text-gray-500">
          <div class="flex items-start gap-2">
            <span class="flex-shrink-0 w-5 h-5 rounded-full bg-primary text-white flex items-center justify-center text-xs font-bold">1</span>
            <span>Le contenu est hache en SHA-256 pour garantir son integrite</span>
          </div>
          <div class="flex items-start gap-2">
            <span class="flex-shrink-0 w-5 h-5 rounded-full bg-primary text-white flex items-center justify-center text-xs font-bold">2</span>
            <span>Le document est epingle sur IPFS (Kubo) pour le stockage distribue</span>
          </div>
          <div class="flex items-start gap-2">
            <span class="flex-shrink-0 w-5 h-5 rounded-full bg-primary text-white flex items-center justify-center text-xs font-bold">3</span>
            <span>Le hash est ancre on-chain via system.remark sur Duniter V2</span>
          </div>
        </div>
      </div>
    </UCard>
  </div>
</template>
