<script setup lang="ts">
import type { DocumentItem } from '~/stores/documents'

const route = useRoute()
const documents = useDocumentsStore()
const auth = useAuthStore()

const slug = computed(() => route.params.slug as string)

const archiving = ref(false)

onMounted(async () => {
  await documents.fetchBySlug(slug.value)
})

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

watch(slug, async (newSlug) => {
  if (newSlug) {
    await documents.fetchBySlug(newSlug)
  }
})

const typeLabel = (docType: string) => {
  switch (docType) {
    case 'licence': return 'Licence'
    case 'engagement': return 'Engagement'
    case 'reglement': return 'Reglement'
    case 'constitution': return 'Constitution'
    default: return docType
  }
}

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

function handlePropose(item: DocumentItem) {
  navigateTo(`/documents/${slug.value}/items/${item.id}`)
}

async function archiveToSanctuary() {
  archiving.value = true
  try {
    await documents.archiveDocument(slug.value)
  } catch {
    // Error handled in store
  } finally {
    archiving.value = false
  }
}
</script>

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

    <!-- Loading state -->
    <template v-if="documents.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 5" :key="i" class="h-24 w-full" />
        </div>
      </div>
    </template>

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

    <!-- Document detail -->
    <template v-else-if="documents.current">
      <!-- Header -->
      <div>
        <div class="flex items-start justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              {{ documents.current.title }}
            </h1>
            <div class="flex items-center gap-3 mt-2">
              <UBadge variant="subtle" color="primary">
                {{ typeLabel(documents.current.doc_type) }}
              </UBadge>
              <CommonStatusBadge :status="documents.current.status" type="document" />
              <span class="text-sm text-gray-500 font-mono">
                v{{ documents.current.version }}
              </span>
            </div>
          </div>

          <!-- Archive button for authenticated users with active documents -->
          <div v-if="auth.isAuthenticated && documents.current.status === 'active'" class="flex items-center gap-2">
            <UButton
              label="Archiver dans le Sanctuaire"
              icon="i-lucide-archive"
              color="primary"
              variant="soft"
              :loading="archiving"
              @click="archiveToSanctuary"
            />
          </div>
        </div>

        <!-- Description -->
        <p v-if="documents.current.description" class="mt-4 text-gray-600 dark:text-gray-400">
          {{ documents.current.description }}
        </p>
      </div>

      <!-- Metadata -->
      <UCard>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div>
            <p class="text-gray-500">Cree le</p>
            <p class="font-medium text-gray-900 dark:text-white">
              {{ formatDate(documents.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(documents.current.updated_at) }}
            </p>
          </div>
          <div>
            <p class="text-gray-500">Nombre d'items</p>
            <p class="font-medium text-gray-900 dark:text-white">
              {{ documents.current.items_count }}
            </p>
          </div>
          <div>
            <p class="text-gray-500">Ancrage IPFS</p>
            <div class="mt-1">
              <SanctuaryIPFSLink :cid="documents.current.ipfs_cid" />
            </div>
          </div>
        </div>

        <!-- Chain anchor info -->
        <div v-if="documents.current.chain_anchor" class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-800">
          <div class="flex items-center gap-2">
            <p class="text-sm text-gray-500">Ancrage on-chain :</p>
            <SanctuaryChainAnchor :tx-hash="documents.current.chain_anchor" :block="null" />
          </div>
        </div>
      </UCard>

      <!-- Document items -->
      <div>
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Contenu du document ({{ documents.items.length }} items)
        </h2>

        <div v-if="documents.items.length === 0" class="text-center py-8">
          <UIcon name="i-lucide-file-plus" class="text-4xl text-gray-400 mb-3" />
          <p class="text-gray-500">Aucun item dans ce document</p>
        </div>

        <div v-else class="space-y-4">
          <DocumentsItemCard
            v-for="item in documents.items"
            :key="item.id"
            :item="item"
            :document-slug="slug"
            :show-actions="auth.isAuthenticated"
            @propose="handlePropose"
          />
        </div>
      </div>
    </template>
  </div>
</template>
