<script lang="ts" setup>
import { Link, router } from '@inertiajs/vue3'
import { ref, watch } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import type { KnowledgeBaseArticle, KnowledgeBaseCategory, PaginatedResponse, StatusColor } from '@/types'

interface Props {
  articles: PaginatedResponse<KnowledgeBaseArticle & { helpful_percentage: number }>
  categories: Pick<KnowledgeBaseCategory, 'id' | 'name'>[]
  filters: {
    search: string
    category: string
    status: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const categoryFilter = ref<string>(props.filters.category)
const statusFilter = ref<string>(props.filters.status)

const categoryFilterItems = [
  { title: 'All Categories', value: 'all' },
  ...props.categories.map(c => ({ title: c.name, value: String(c.id) })),
]

const statusFilterItems = [
  { title: 'All Statuses', value: 'all' },
  { title: 'Draft', value: 'draft' },
  { title: 'Published', value: 'published' },
  { title: 'Archived', value: 'archived' },
]

const tableHeaders = [
  { title: 'Title', key: 'title', sortable: true },
  { title: 'Category', key: 'category', sortable: false },
  { title: 'Status', key: 'status', sortable: true },
  { title: 'Views', key: 'view_count', sortable: true, align: 'center' as const },
  { title: 'Helpful %', key: 'helpful_percentage', sortable: false, align: 'center' as const },
  { title: 'Author', key: 'author', sortable: false },
  { title: 'Published', key: 'published_at', sortable: true },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
]

function resolveStatusColor(status: string): StatusColor {
  const map: Record<string, StatusColor> = {
    draft: 'warning',
    published: 'success',
    archived: 'secondary',
  }
  return map[status] ?? 'info'
}

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 applyFilters(): void {
  router.get('/knowledge-base/articles', {
    search: search.value || undefined,
    category: categoryFilter.value !== 'all' ? categoryFilter.value : undefined,
    status: statusFilter.value !== 'all' ? statusFilter.value : undefined,
  }, {
    preserveState: true,
    replace: true,
  })
}

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

watch(search, () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => applyFilters(), 300)
})

watch([categoryFilter, statusFilter], () => {
  applyFilters()
})

function deleteArticle(article: KnowledgeBaseArticle): void {
  if (confirm(`Are you sure you want to delete "${article.title}"? This action cannot be undone.`)) {
    router.delete(`/knowledge-base/articles/${article.id}`, {
      preserveScroll: true,
    })
  }
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          KB Articles
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage knowledge base articles
        </div>
      </div>
      <div class="d-flex gap-3">
        <Link href="/knowledge-base/categories">
          <VBtn variant="outlined" prepend-icon="tabler-folder">
            Categories
          </VBtn>
        </Link>
        <Link href="/knowledge-base/articles/create">
          <VBtn color="primary" prepend-icon="tabler-plus">
            Create Article
          </VBtn>
        </Link>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="4">
            <VTextField
              v-model="search"
              placeholder="Search by title..."
              prepend-inner-icon="tabler-search"
              clearable
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="categoryFilter"
              :items="categoryFilterItems"
              placeholder="Filter by category"
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="statusFilter"
              :items="statusFilterItems"
              placeholder="Filter by status"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Articles Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="articles.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <!-- Title -->
        <template #item.title="{ item }">
          <Link :href="`/knowledge-base/articles/${item.id}`" class="text-decoration-none">
            <span class="font-weight-medium">{{ item.title }}</span>
          </Link>
          <VChip
            v-if="item.is_featured"
            color="warning"
            size="x-small"
            variant="tonal"
            class="ms-2"
          >
            Featured
          </VChip>
        </template>

        <!-- Category -->
        <template #item.category="{ item }">
          <span v-if="item.category">{{ item.category.name }}</span>
          <span v-else class="text-medium-emphasis">--</span>
        </template>

        <!-- Status -->
        <template #item.status="{ item }">
          <VChip
            :color="resolveStatusColor(item.status)"
            size="small"
            variant="tonal"
            class="text-capitalize"
          >
            {{ item.status }}
          </VChip>
        </template>

        <!-- Views -->
        <template #item.view_count="{ item }">
          {{ item.view_count.toLocaleString() }}
        </template>

        <!-- Helpful % -->
        <template #item.helpful_percentage="{ item }">
          <span v-if="item.helpful_count + item.not_helpful_count > 0">
            {{ item.helpful_percentage }}%
          </span>
          <span v-else class="text-medium-emphasis">--</span>
        </template>

        <!-- Author -->
        <template #item.author="{ item }">
          <span v-if="item.author">{{ item.author.name }}</span>
          <span v-else class="text-medium-emphasis">--</span>
        </template>

        <!-- Published -->
        <template #item.published_at="{ item }">
          {{ formatDate(item.published_at) }}
        </template>

        <!-- Actions -->
        <template #item.actions="{ item }">
          <VMenu>
            <template #activator="{ props: menuProps }">
              <VBtn
                icon="tabler-dots-vertical"
                variant="text"
                size="small"
                v-bind="menuProps"
              />
            </template>
            <VList density="compact">
              <Link :href="`/knowledge-base/articles/${item.id}`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-eye">
                  <VListItemTitle>View</VListItemTitle>
                </VListItem>
              </Link>
              <Link :href="`/knowledge-base/articles/${item.id}/edit`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-edit">
                  <VListItemTitle>Edit</VListItemTitle>
                </VListItem>
              </Link>
              <VListItem
                prepend-icon="tabler-trash"
                class="text-error"
                @click="deleteArticle(item)"
              >
                <VListItemTitle>Delete</VListItemTitle>
              </VListItem>
            </VList>
          </VMenu>
        </template>

        <!-- No data -->
        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-article" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No articles found. Create your first article to get started.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
