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

interface SanctuaryEntryDetail {
  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
}

interface VerifyResult {
  match: boolean
  message: string
}

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

const entry = ref<SanctuaryEntryDetail | null>(null)
const loading = ref(true)
const error = ref<string | null>(null)

const verifying = ref(false)
const verifyResult = ref<VerifyResult | null>(null)

const copied = ref<string | null>(null)

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

  try {
    entry.value = await $api<SanctuaryEntryDetail>(`/sanctuary/${entryId.value}`)
  } catch (err: any) {
    error.value = err?.data?.detail || err?.message || 'Entree introuvable'
  } finally {
    loading.value = false
  }
}

async function verifyIntegrity() {
  verifying.value = true
  verifyResult.value = null

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

async function copyToClipboard(text: string, field: string) {
  try {
    await navigator.clipboard.writeText(text)
    copied.value = field
    setTimeout(() => { copied.value = null }, 2000)
  } catch {
    // Clipboard API not available
  }
}

onMounted(() => {
  loadEntry()
})

watch(entryId, () => {
  loadEntry()
})

const typeLabel = (entryType: string): 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): 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',
  })
}

const parsedMetadata = computed(() => {
  if (!entry.value?.metadata_json) return null
  try {
    return JSON.parse(entry.value.metadata_json)
  } catch {
    return null
  }
})

const formattedMetadata = computed(() => {
  if (!parsedMetadata.value) return null
  return JSON.stringify(parsedMetadata.value, null, 2)
})

const IPFS_GATEWAY = 'https://ipfs.io/ipfs/'
</script>

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

    <!-- Loading state -->
    <template v-if="loading">
      <div class="space-y-4">
        <USkeleton class="h-8 w-96" />
        <USkeleton class="h-4 w-64" />
        <USkeleton class="h-48 w-full" />
        <USkeleton class="h-32 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>

    <!-- Entry detail -->
    <template v-else-if="entry">
      <!-- Header -->
      <div class="flex items-start justify-between">
        <div>
          <div class="flex items-center gap-3 mb-2">
            <UIcon name="i-lucide-shield-check" class="text-2xl text-primary" />
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              {{ entry.title || 'Entree sans titre' }}
            </h1>
          </div>
          <div class="flex items-center gap-3">
            <UBadge :color="(typeColor(entry.entry_type) as any)" variant="subtle">
              {{ typeLabel(entry.entry_type) }}
            </UBadge>
            <span class="text-sm text-gray-500">
              {{ formatDate(entry.created_at) }}
            </span>
          </div>
        </div>

        <!-- Verify button -->
        <UButton
          label="Verifier l'integrite"
          icon="i-lucide-shield-check"
          color="primary"
          :loading="verifying"
          @click="verifyIntegrity"
        />
      </div>

      <!-- Verification result -->
      <UCard v-if="verifyResult">
        <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-2xl' : 'text-red-500 text-2xl'"
          />
          <div>
            <p
              :class="verifyResult.match
                ? 'text-green-700 dark:text-green-400 font-semibold'
                : 'text-red-700 dark:text-red-400 font-semibold'"
            >
              {{ verifyResult.match ? 'Integrite verifiee avec succes' : 'Verification echouee' }}
            </p>
            <p class="text-sm text-gray-500 mt-1">{{ verifyResult.message }}</p>
          </div>
        </div>
      </UCard>

      <!-- SHA-256 Hash -->
      <UCard>
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2">
              <UIcon name="i-lucide-hash" class="text-gray-400" />
              <h2 class="text-sm font-semibold text-gray-500 uppercase">Hash SHA-256</h2>
            </div>
            <UButton
              :icon="copied === 'hash' ? 'i-lucide-check' : 'i-lucide-copy'"
              :label="copied === 'hash' ? 'Copie' : 'Copier'"
              variant="ghost"
              color="neutral"
              size="xs"
              @click="copyToClipboard(entry.content_hash, 'hash')"
            />
          </div>
          <div class="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-4">
            <p class="font-mono text-sm text-gray-700 dark:text-gray-300 break-all select-all">
              {{ entry.content_hash }}
            </p>
          </div>
        </div>
      </UCard>

      <!-- IPFS CID -->
      <UCard>
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2">
              <UIcon name="i-lucide-hard-drive" class="text-gray-400" />
              <h2 class="text-sm font-semibold text-gray-500 uppercase">IPFS CID</h2>
            </div>
            <UButton
              v-if="entry.ipfs_cid"
              :icon="copied === 'ipfs' ? 'i-lucide-check' : 'i-lucide-copy'"
              :label="copied === 'ipfs' ? 'Copie' : 'Copier'"
              variant="ghost"
              color="neutral"
              size="xs"
              @click="copyToClipboard(entry.ipfs_cid!, 'ipfs')"
            />
          </div>
          <template v-if="entry.ipfs_cid">
            <div class="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-4">
              <p class="font-mono text-sm text-gray-700 dark:text-gray-300 break-all select-all">
                {{ entry.ipfs_cid }}
              </p>
            </div>
            <a
              :href="`${IPFS_GATEWAY}${entry.ipfs_cid}`"
              target="_blank"
              rel="noopener noreferrer"
              class="inline-flex items-center gap-2 text-sm text-primary hover:underline"
            >
              <UIcon name="i-lucide-external-link" />
              <span>Ouvrir sur la passerelle IPFS</span>
            </a>
          </template>
          <template v-else>
            <div class="bg-yellow-50 dark:bg-yellow-900/10 rounded-lg p-4">
              <div class="flex items-center gap-2">
                <UIcon name="i-lucide-clock" class="text-yellow-500" />
                <p class="text-sm text-yellow-700 dark:text-yellow-400">
                  En attente d'epinglage IPFS
                </p>
              </div>
            </div>
          </template>
        </div>
      </UCard>

      <!-- Chain Anchor -->
      <UCard>
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2">
              <UIcon name="i-lucide-link" class="text-gray-400" />
              <h2 class="text-sm font-semibold text-gray-500 uppercase">Ancrage On-chain</h2>
            </div>
            <UButton
              v-if="entry.chain_tx_hash"
              :icon="copied === 'chain' ? 'i-lucide-check' : 'i-lucide-copy'"
              :label="copied === 'chain' ? 'Copie' : 'Copier'"
              variant="ghost"
              color="neutral"
              size="xs"
              @click="copyToClipboard(entry.chain_tx_hash!, 'chain')"
            />
          </div>
          <template v-if="entry.chain_tx_hash">
            <div class="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-4 space-y-2">
              <div>
                <p class="text-xs text-gray-500 mb-1">TX Hash</p>
                <p class="font-mono text-sm text-gray-700 dark:text-gray-300 break-all select-all">
                  {{ entry.chain_tx_hash }}
                </p>
              </div>
              <div v-if="entry.chain_block">
                <p class="text-xs text-gray-500 mb-1">Numero de bloc</p>
                <p class="font-mono text-sm text-gray-700 dark:text-gray-300">
                  #{{ entry.chain_block.toLocaleString('fr-FR') }}
                </p>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="bg-yellow-50 dark:bg-yellow-900/10 rounded-lg p-4">
              <div class="flex items-center gap-2">
                <UIcon name="i-lucide-clock" class="text-yellow-500" />
                <p class="text-sm text-yellow-700 dark:text-yellow-400">
                  En attente d'ancrage on-chain via system.remark
                </p>
              </div>
            </div>
          </template>
        </div>
      </UCard>

      <!-- Verification status -->
      <UCard>
        <div class="space-y-3">
          <div class="flex items-center gap-2">
            <UIcon name="i-lucide-check-circle" class="text-gray-400" />
            <h2 class="text-sm font-semibold text-gray-500 uppercase">Statut de verification</h2>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="flex items-center gap-3 p-3 rounded-lg"
              :class="entry.content_hash
                ? 'bg-green-50 dark:bg-green-900/10'
                : 'bg-gray-50 dark:bg-gray-800/50'"
            >
              <UIcon
                :name="entry.content_hash ? 'i-lucide-check-circle' : 'i-lucide-clock'"
                :class="entry.content_hash ? 'text-green-500' : 'text-gray-400'"
              />
              <div>
                <p class="text-sm font-medium" :class="entry.content_hash ? 'text-green-700 dark:text-green-400' : 'text-gray-500'">
                  Hash SHA-256
                </p>
                <p class="text-xs text-gray-500">
                  {{ entry.content_hash ? 'Calcule' : 'En attente' }}
                </p>
              </div>
            </div>

            <div class="flex items-center gap-3 p-3 rounded-lg"
              :class="entry.ipfs_cid
                ? 'bg-green-50 dark:bg-green-900/10'
                : 'bg-yellow-50 dark:bg-yellow-900/10'"
            >
              <UIcon
                :name="entry.ipfs_cid ? 'i-lucide-check-circle' : 'i-lucide-clock'"
                :class="entry.ipfs_cid ? 'text-green-500' : 'text-yellow-500'"
              />
              <div>
                <p class="text-sm font-medium" :class="entry.ipfs_cid ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'">
                  IPFS
                </p>
                <p class="text-xs text-gray-500">
                  {{ entry.ipfs_cid ? 'Epingle' : 'En attente' }}
                </p>
              </div>
            </div>

            <div class="flex items-center gap-3 p-3 rounded-lg"
              :class="entry.chain_tx_hash
                ? 'bg-green-50 dark:bg-green-900/10'
                : 'bg-yellow-50 dark:bg-yellow-900/10'"
            >
              <UIcon
                :name="entry.chain_tx_hash ? 'i-lucide-check-circle' : 'i-lucide-clock'"
                :class="entry.chain_tx_hash ? 'text-green-500' : 'text-yellow-500'"
              />
              <div>
                <p class="text-sm font-medium" :class="entry.chain_tx_hash ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'">
                  On-chain
                </p>
                <p class="text-xs text-gray-500">
                  {{ entry.chain_tx_hash ? 'Ancre' : 'En attente' }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </UCard>

      <!-- Metadata JSON -->
      <UCard v-if="entry.metadata_json">
        <div class="space-y-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2">
              <UIcon name="i-lucide-braces" class="text-gray-400" />
              <h2 class="text-sm font-semibold text-gray-500 uppercase">Metadonnees</h2>
            </div>
            <UButton
              v-if="entry.metadata_json"
              :icon="copied === 'metadata' ? 'i-lucide-check' : 'i-lucide-copy'"
              :label="copied === 'metadata' ? 'Copie' : 'Copier'"
              variant="ghost"
              color="neutral"
              size="xs"
              @click="copyToClipboard(entry.metadata_json!, 'metadata')"
            />
          </div>
          <div class="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-4 overflow-x-auto">
            <pre class="font-mono text-xs text-gray-700 dark:text-gray-300">{{ formattedMetadata || entry.metadata_json }}</pre>
          </div>
        </div>
      </UCard>

      <!-- Reference info -->
      <UCard>
        <div class="space-y-3">
          <div class="flex items-center gap-2">
            <UIcon name="i-lucide-info" class="text-gray-400" />
            <h2 class="text-sm font-semibold text-gray-500 uppercase">Reference</h2>
          </div>
          <div class="grid grid-cols-2 gap-4 text-sm">
            <div>
              <p class="text-gray-500">Identifiant</p>
              <p class="font-mono text-xs text-gray-700 dark:text-gray-300">{{ entry.id }}</p>
            </div>
            <div>
              <p class="text-gray-500">Reference (document/decision)</p>
              <p class="font-mono text-xs text-gray-700 dark:text-gray-300">{{ entry.reference_id }}</p>
            </div>
          </div>
        </div>
      </UCard>
    </template>
  </div>
</template>
