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

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

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

const docTypeOptions = [
  { label: 'Tous les types', value: undefined },
  { label: 'Licence', value: 'licence' },
  { label: 'Engagement', value: 'engagement' },
  { label: 'Reglement', value: 'reglement' },
  { label: 'Constitution', value: 'constitution' },
]

const statusOptions = [
  { label: 'Tous les statuts', value: undefined },
  { label: 'Brouillon', value: 'draft' },
  { label: 'Actif', value: 'active' },
  { label: 'Archive', value: 'archived' },
]

// New document modal state
const showNewDocModal = ref(false)
const newDoc = ref<DocumentCreate>({
  slug: '',
  title: '',
  doc_type: 'licence',
  description: null,
  version: '1.0.0',
})
const creating = ref(false)

const newDocTypeOptions = [
  { label: 'Licence', value: 'licence' },
  { label: 'Engagement', value: 'engagement' },
  { label: 'Reglement', value: 'reglement' },
  { label: 'Constitution', value: 'constitution' },
]

async function loadDocuments() {
  await documents.fetchAll({
    doc_type: filterType.value,
    status: filterStatus.value,
  })
}

onMounted(() => {
  loadDocuments()
})

watch([filterType, filterStatus], () => {
  loadDocuments()
})

function openNewDocModal() {
  newDoc.value = {
    slug: '',
    title: '',
    doc_type: 'licence',
    description: null,
    version: '1.0.0',
  }
  showNewDocModal.value = true
}

function generateSlug(title: string): string {
  return title
    .toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
    .slice(0, 64)
}

watch(() => newDoc.value.title, (title) => {
  if (title) {
    newDoc.value.slug = generateSlug(title)
  }
})

async function createDocument() {
  creating.value = true
  try {
    const doc = await documents.createDocument(newDoc.value)
    showNewDocModal.value = false
    if (doc) {
      navigateTo(`/documents/${doc.slug}`)
    }
  } catch {
    // Error handled in store
  } finally {
    creating.value = false
  }
}
</script>

<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
          Documents de reference
        </h1>
        <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
          Documents fondateurs de la communaute Duniter/G1 sous vote permanent
        </p>
      </div>

      <!-- New document button for authenticated users -->
      <UButton
        v-if="auth.isAuthenticated"
        label="Nouveau document"
        icon="i-lucide-plus"
        color="primary"
        @click="openNewDocModal"
      />
    </div>

    <!-- Filters -->
    <div class="flex flex-wrap gap-4">
      <USelect
        v-model="filterType"
        :items="docTypeOptions"
        placeholder="Type de document"
        class="w-48"
      />
      <USelect
        v-model="filterStatus"
        :items="statusOptions"
        placeholder="Statut"
        class="w-48"
      />
    </div>

    <!-- Error state -->
    <template v-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 list component -->
    <DocumentsDocumentList
      :documents="documents.list"
      :loading="documents.loading"
    />

    <!-- New document modal -->
    <UModal v-model:open="showNewDocModal">
      <template #content>
        <div class="p-6 space-y-4">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
            Nouveau document de reference
          </h3>

          <div class="space-y-4">
            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Titre
              </label>
              <UInput
                v-model="newDoc.title"
                placeholder="Ex: Licence G1"
                class="w-full"
              />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Slug (identifiant URL)
              </label>
              <UInput
                v-model="newDoc.slug"
                placeholder="Ex: licence-g1"
                class="w-full font-mono text-sm"
              />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Type de document
              </label>
              <USelect
                v-model="newDoc.doc_type"
                :items="newDocTypeOptions"
                class="w-full"
              />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Version
              </label>
              <UInput
                v-model="newDoc.version"
                placeholder="1.0.0"
                class="w-full font-mono text-sm"
              />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Description (optionnelle)
              </label>
              <UTextarea
                v-model="newDoc.description"
                :rows="3"
                placeholder="Decrivez brievement ce document..."
                class="w-full"
              />
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 pt-2">
            <UButton
              label="Annuler"
              variant="ghost"
              color="neutral"
              @click="showNewDocModal = false"
            />
            <UButton
              label="Creer le document"
              icon="i-lucide-plus"
              color="primary"
              :loading="creating"
              :disabled="!newDoc.title.trim() || !newDoc.slug.trim()"
              @click="createDocument"
            />
          </div>
        </div>
      </template>
    </UModal>
  </div>
</template>
