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

interface SanctuaryEntry {
  id: string
  entry_type: string
  reference_id: string
  title: string | null
  content_hash: string
  ipfs_cid: string | null
  chain_tx_hash: string | null
  chain_block: number | null
  metadata_json: string | null
  created_at: string
}

const entries = ref<SanctuaryEntry[]>([])
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' },
]

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<SanctuaryEntry[]>('/sanctuary/', { query })
  } catch (err: any) {
    error.value = err?.data?.detail || err?.message || 'Erreur lors du chargement des entrees'
  } finally {
    loading.value = false
  }
}

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

watch(filterType, () => {
  loadEntries()
})

const typeLabel = (entryType: string) => {
  switch (entryType) {
    case 'document': return 'Document'
    case 'decision': return 'Decision'
    case 'vote_result': return 'Resultat de vote'
    default: return entryType
  }
}

const typeColor = (entryType: string) => {
  switch (entryType) {
    case 'document': return 'primary'
    case 'decision': return 'success'
    case 'vote_result': return 'info'
    default: return 'neutral'
  }
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('fr-FR', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function truncateHash(hash: string | null, length: number = 16): string {
  if (!hash) return '-'
  if (hash.length <= length * 2) return hash
  return hash.slice(0, length) + '...' + hash.slice(-8)
}
</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>

    <!-- Loading state -->
    <template v-if="loading">
      <div class="space-y-3">
        <USkeleton v-for="i in 4" :key="i" class="h-24 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 -->
    <template v-else>
      <div class="space-y-4">
        <UCard
          v-for="entry in entries"
          :key="entry.id"
        >
          <div class="space-y-4">
            <!-- Entry header -->
            <div class="flex items-start justify-between">
              <div class="flex items-center gap-3">
                <UIcon name="i-lucide-shield-check" class="text-xl text-primary" />
                <div>
                  <h3 class="font-semibold text-gray-900 dark:text-white">
                    {{ entry.title || 'Entree sans titre' }}
                  </h3>
                  <p class="text-xs text-gray-500">
                    {{ formatDate(entry.created_at) }}
                  </p>
                </div>
              </div>
              <UBadge :color="typeColor(entry.entry_type)" variant="subtle" size="xs">
                {{ typeLabel(entry.entry_type) }}
              </UBadge>
            </div>

            <!-- Hashes and anchors -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <!-- Content hash -->
              <div class="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div class="flex items-center gap-2 mb-1">
                  <UIcon name="i-lucide-hash" class="text-gray-400 text-sm" />
                  <span class="text-xs font-semibold text-gray-500 uppercase">SHA-256</span>
                </div>
                <p class="font-mono text-xs text-gray-700 dark:text-gray-300 break-all">
                  {{ truncateHash(entry.content_hash) }}
                </p>
              </div>

              <!-- IPFS CID -->
              <div class="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div class="flex items-center gap-2 mb-1">
                  <UIcon name="i-lucide-hard-drive" class="text-gray-400 text-sm" />
                  <span class="text-xs font-semibold text-gray-500 uppercase">IPFS CID</span>
                </div>
                <template v-if="entry.ipfs_cid">
                  <p class="font-mono text-xs text-gray-700 dark:text-gray-300 break-all">
                    {{ truncateHash(entry.ipfs_cid) }}
                  </p>
                </template>
                <template v-else>
                  <p class="text-xs text-gray-400 italic">En attente d'epinglage</p>
                </template>
              </div>

              <!-- Chain anchor -->
              <div class="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                <div class="flex items-center gap-2 mb-1">
                  <UIcon name="i-lucide-link" class="text-gray-400 text-sm" />
                  <span class="text-xs font-semibold text-gray-500 uppercase">On-chain</span>
                </div>
                <template v-if="entry.chain_tx_hash">
                  <p class="font-mono text-xs text-gray-700 dark:text-gray-300 break-all">
                    {{ truncateHash(entry.chain_tx_hash) }}
                  </p>
                  <p v-if="entry.chain_block" class="text-xs text-gray-400 mt-0.5">
                    Bloc #{{ entry.chain_block.toLocaleString('fr-FR') }}
                  </p>
                </template>
                <template v-else>
                  <p class="text-xs text-gray-400 italic">En attente d'ancrage</p>
                </template>
              </div>
            </div>

            <!-- Verification status -->
            <div class="flex items-center gap-4 text-xs">
              <div class="flex items-center gap-1">
                <UIcon
                  :name="entry.ipfs_cid ? 'i-lucide-check-circle' : 'i-lucide-clock'"
                  :class="entry.ipfs_cid ? 'text-green-500' : 'text-gray-400'"
                />
                <span :class="entry.ipfs_cid ? 'text-green-600' : 'text-gray-400'">
                  IPFS {{ entry.ipfs_cid ? 'epingle' : 'en attente' }}
                </span>
              </div>
              <div class="flex items-center gap-1">
                <UIcon
                  :name="entry.chain_tx_hash ? 'i-lucide-check-circle' : 'i-lucide-clock'"
                  :class="entry.chain_tx_hash ? 'text-green-500' : 'text-gray-400'"
                />
                <span :class="entry.chain_tx_hash ? 'text-green-600' : 'text-gray-400'">
                  Chain {{ entry.chain_tx_hash ? 'ancre' : 'en attente' }}
                </span>
              </div>
            </div>
          </div>
        </UCard>
      </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>
