<script lang="ts" setup>
import { Head, Link, router } from '@inertiajs/vue3'
import { ref } from 'vue'
import MarketingLayout from '@/Layouts/MarketingLayout.vue'
import HeroSection from '@/Components/Marketing/HeroSection.vue'
import SectionHeader from '@/Components/Marketing/SectionHeader.vue'
import ScrollReveal from '@/Components/Marketing/ScrollReveal.vue'
import type { KnowledgeBaseArticle, KnowledgeBaseCategory } from '@/types'

interface Props {
  categories: KnowledgeBaseCategory[]
  featuredArticles: KnowledgeBaseArticle[]
}

defineOptions({ layout: MarketingLayout })

const props = defineProps<Props>()

const searchQuery = ref<string>('')
const searchResults = ref<KnowledgeBaseArticle[]>([])
const isSearching = ref<boolean>(false)

let searchTimeout: ReturnType<typeof setTimeout> | null = null

function onSearch(): void {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }

  if (searchQuery.value.length < 2) {
    searchResults.value = []
    return
  }

  searchTimeout = setTimeout(async () => {
    isSearching.value = true
    try {
      const response = await fetch(`/knowledge-base/search?q=${encodeURIComponent(searchQuery.value)}`)
      const data = await response.json()
      searchResults.value = data.articles
    } catch {
      searchResults.value = []
    } finally {
      isSearching.value = false
    }
  }, 300)
}

function goToSearch(): void {
  if (searchQuery.value.length >= 2) {
    onSearch()
  }
}

function formatDate(dateString: string | null): string {
  if (!dateString) {
    return ''
  }
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

function getTotalArticles(category: KnowledgeBaseCategory): number {
  let count = category.articles_count ?? 0
  if (category.children) {
    for (const child of category.children) {
      count += child.articles_count ?? 0
    }
  }
  return count
}
</script>

<template>
  <Head title="Knowledge Base | EZSCALE" />
  <div>
    <!-- Hero -->
    <HeroSection>
      <template #content>
        <h1 class="text-h3 text-md-h2 font-weight-bold mb-3">
          Knowledge <span class="hero-gradient-text">Base</span>
        </h1>
        <p class="text-body-1 text-medium-emphasis font-weight-regular mb-6" style="max-inline-size: 540px;">
          Find answers to common questions, guides, and tutorials to help you get the most out of EZSCALE.
        </p>

        <!-- Search -->
        <VTextField
          v-model="searchQuery"
          placeholder="Search articles..."
          prepend-inner-icon="tabler-search"
          variant="solo"
          bg-color="surface"
          style="max-inline-size: 500px;"
          clearable
          @update:model-value="onSearch"
          @keyup.enter="goToSearch"
        />

        <!-- Search Results Dropdown -->
        <VCard
          v-if="searchResults.length > 0 || isSearching"
          class="mt-2"
          style="max-inline-size: 500px;"
          elevation="8"
        >
          <VList v-if="!isSearching" density="compact">
            <VListItem
              v-for="result in searchResults"
              :key="result.id"
              :href="`/knowledge-base/${result.category?.slug}/${result.slug}`"
              class="text-decoration-none"
            >
              <VListItemTitle class="font-weight-medium">{{ result.title }}</VListItemTitle>
              <VListItemSubtitle v-if="result.category">
                {{ result.category.name }}
              </VListItemSubtitle>
            </VListItem>
          </VList>
          <VCardText v-else class="text-center py-4">
            <VProgressCircular indeterminate size="24" class="me-2" />
            Searching...
          </VCardText>
        </VCard>
      </template>
    </HeroSection>

    <!-- Featured Articles -->
    <div v-if="featuredArticles.length > 0" class="section-alt-bg py-16">
      <VContainer>
        <ScrollReveal>
          <SectionHeader
            label="Featured"
            title="Popular Articles"
            subtitle="Our most helpful guides and tutorials."
          />

          <VRow>
            <VCol
              v-for="(article, index) in featuredArticles"
              :key="article.id"
              cols="12"
              sm="6"
              md="4"
            >
              <Link
                :href="`/knowledge-base/${article.category?.slug}/${article.slug}`"
                class="text-decoration-none"
              >
                <VCard
                  variant="outlined"
                  :class="`h-100 feature-card-hover fade-in-up stagger-${index + 1}`"
                >
                  <VCardText class="pa-5">
                    <VChip
                      v-if="article.category"
                      color="primary"
                      size="x-small"
                      variant="tonal"
                      class="mb-3"
                    >
                      {{ article.category.name }}
                    </VChip>
                    <h3 class="text-subtitle-1 font-weight-bold mb-2">{{ article.title }}</h3>
                    <p v-if="article.excerpt" class="text-body-2 text-medium-emphasis mb-3">
                      {{ article.excerpt }}
                    </p>
                    <div class="d-flex align-center gap-3 text-caption text-medium-emphasis">
                      <span>
                        <VIcon icon="tabler-eye" size="14" class="me-1" />
                        {{ article.view_count }}
                      </span>
                      <span v-if="article.published_at">{{ formatDate(article.published_at) }}</span>
                    </div>
                  </VCardText>
                </VCard>
              </Link>
            </VCol>
          </VRow>
        </ScrollReveal>
      </VContainer>
    </div>

    <!-- Categories -->
    <VContainer class="py-16">
      <ScrollReveal>
        <SectionHeader
          label="Browse"
          title="Browse by Category"
          subtitle="Explore our knowledge base by topic."
        />

        <VRow>
          <VCol
            v-for="(category, index) in categories"
            :key="category.id"
            cols="12"
            sm="6"
            md="4"
          >
            <Link
              :href="`/knowledge-base/${category.slug}`"
              class="text-decoration-none"
            >
              <VCard
                variant="outlined"
                :class="`h-100 feature-card-hover fade-in-up stagger-${index + 1}`"
              >
                <VCardText class="pa-5 text-center">
                  <VAvatar
                    color="primary"
                    variant="tonal"
                    size="52"
                    class="mb-4"
                  >
                    <VIcon :icon="category.icon || 'tabler-folder'" size="26" />
                  </VAvatar>
                  <h3 class="text-h6 font-weight-bold mb-2">{{ category.name }}</h3>
                  <p v-if="category.description" class="text-body-2 text-medium-emphasis mb-3">
                    {{ category.description }}
                  </p>
                  <VChip size="small" variant="tonal" color="info">
                    {{ getTotalArticles(category) }} {{ getTotalArticles(category) === 1 ? 'article' : 'articles' }}
                  </VChip>
                </VCardText>
              </VCard>
            </Link>
          </VCol>
        </VRow>

        <!-- Empty state -->
        <div v-if="categories.length === 0" class="text-center py-12">
          <VIcon icon="tabler-book-off" size="64" color="disabled" class="mb-4" />
          <h3 class="text-h6 text-medium-emphasis mb-2">No categories yet</h3>
          <p class="text-body-2 text-medium-emphasis">
            Our knowledge base is being built. Check back soon!
          </p>
        </div>
      </ScrollReveal>
    </VContainer>
  </div>
</template>
