<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useQuery } from '@tanstack/vue-query'
import { useAuthStore } from '@/stores/auth'
import { fetchSearch } from '@/api/search'
import type { FacetCounts, SpecSearchResult } from '@/api/types'
import StatusBadge from '@/components/common/StatusBadge.vue'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const org = computed(() => (route.params.org as string) || auth.org)

const PAGE_SIZE = 20

// Filter state from query params
const query = ref((route.query.q as string) || '')
const filterStatus = ref((route.query.status as string) || '')
const filterTeam = ref((route.query.team as string) || '')
const filterTag = ref((route.query.tag as string) || '')
const filterRepo = ref((route.query.repo as string) || '')
const page = ref(Number(route.query.page) || 1)

const offset = computed(() => (page.value - 1) * PAGE_SIZE)

const { data, isLoading } = useQuery({
  queryKey: ['search', org, query, filterStatus, filterTeam, filterTag, filterRepo, page],
  queryFn: () => fetchSearch(org.value, {
    q: query.value,
    status: filterStatus.value,
    team: filterTeam.value,
    tag: filterTag.value,
    repo: filterRepo.value,
    limit: PAGE_SIZE,
    offset: offset.value,
  }),
  placeholderData: (prev) => prev,
})

const results = computed<SpecSearchResult[]>(() => data.value?.results ?? [])
const total = computed(() => data.value?.total ?? 0)
const facets = computed<FacetCounts>(() => data.value?.facets ?? { status: {}, repo: {}, team: {}, tag: {} })
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)))

// Sync state to URL
function updateUrl() {
  const q: Record<string, string> = {}
  if (query.value) q.q = query.value
  if (filterStatus.value) q.status = filterStatus.value
  if (filterTeam.value) q.team = filterTeam.value
  if (filterTag.value) q.tag = filterTag.value
  if (filterRepo.value) q.repo = filterRepo.value
  if (page.value > 1) q.page = String(page.value)
  router.replace({ query: q })
}

watch([query, filterStatus, filterTeam, filterTag, filterRepo], () => {
  page.value = 1
  updateUrl()
})
watch(page, updateUrl)

function toggleFacet(facet: 'status' | 'team' | 'tag' | 'repo', value: string) {
  const refs = { status: filterStatus, team: filterTeam, tag: filterTag, repo: filterRepo }
  const r = refs[facet]
  r.value = r.value === value ? '' : value
}

function clearFilters() {
  filterStatus.value = ''
  filterTeam.value = ''
  filterTag.value = ''
  filterRepo.value = ''
  query.value = ''
}

function navigate(result: SpecSearchResult) {
  const path = result.doc_type === 'spec'
    ? `/app/${org.value}/specs/${result.repo_owner}/${result.repo_name}/${result.file_path}`
    : `/app/${org.value}/docs/${result.repo_owner}/${result.repo_name}/${result.file_path}`
  router.push(path)
}

function sortedEntries(obj: Record<string, number>): [string, number][] {
  return Object.entries(obj).sort((a, b) => b[1] - a[1])
}
</script>

<template>
  <div class="max-w-7xl mx-auto px-4 py-6">
    <!-- Search header -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-slate-800 dark:text-slate-100 mb-4">Search</h1>
      <input
        v-model="query"
        type="search"
        placeholder="Search specs and docs..."
        class="w-full bg-surface-light dark:bg-surface-alt border border-border-light dark:border-slate-700 text-slate-800 dark:text-slate-200 placeholder-slate-400 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-500 focus:border-transparent"
      />
    </div>

    <div class="flex gap-6">
      <!-- Facets sidebar -->
      <aside class="w-56 flex-shrink-0 space-y-5">
        <div v-if="filterStatus || filterTeam || filterTag || filterRepo">
          <button class="text-xs text-accent-500 hover:text-accent-600" @click="clearFilters">
            Clear all filters
          </button>
        </div>

        <!-- Status facet -->
        <div v-if="Object.keys(facets.status).length">
          <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Status</h3>
          <ul class="space-y-1">
            <li v-for="[value, count] in sortedEntries(facets.status)" :key="value">
              <button
                class="flex items-center justify-between w-full text-left text-sm px-2 py-1 rounded transition-colors"
                :class="filterStatus === value
                  ? 'bg-accent-50 dark:bg-accent-900/20 text-accent-700 dark:text-accent-300 font-medium'
                  : 'text-slate-700 dark:text-slate-300 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated'"
                @click="toggleFacet('status', value)"
              >
                <span class="flex items-center gap-2">
                  <StatusBadge :status="value" />
                </span>
                <span class="text-xs text-slate-400">{{ count }}</span>
              </button>
            </li>
          </ul>
        </div>

        <!-- Team facet -->
        <div v-if="Object.keys(facets.team).length">
          <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Team</h3>
          <ul class="space-y-1">
            <li v-for="[value, count] in sortedEntries(facets.team)" :key="value">
              <button
                class="flex items-center justify-between w-full text-left text-sm px-2 py-1 rounded transition-colors"
                :class="filterTeam === value
                  ? 'bg-accent-50 dark:bg-accent-900/20 text-accent-700 dark:text-accent-300 font-medium'
                  : 'text-slate-700 dark:text-slate-300 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated'"
                @click="toggleFacet('team', value)"
              >
                <span>{{ value }}</span>
                <span class="text-xs text-slate-400">{{ count }}</span>
              </button>
            </li>
          </ul>
        </div>

        <!-- Repo facet -->
        <div v-if="Object.keys(facets.repo).length">
          <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Repository</h3>
          <ul class="space-y-1">
            <li v-for="[value, count] in sortedEntries(facets.repo)" :key="value">
              <button
                class="flex items-center justify-between w-full text-left text-sm px-2 py-1 rounded transition-colors"
                :class="filterRepo === value
                  ? 'bg-accent-50 dark:bg-accent-900/20 text-accent-700 dark:text-accent-300 font-medium'
                  : 'text-slate-700 dark:text-slate-300 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated'"
                @click="toggleFacet('repo', value)"
              >
                <span class="truncate">{{ value.split('/')[1] || value }}</span>
                <span class="text-xs text-slate-400 flex-shrink-0">{{ count }}</span>
              </button>
            </li>
          </ul>
        </div>

        <!-- Tag facet -->
        <div v-if="Object.keys(facets.tag).length">
          <h3 class="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Tags</h3>
          <ul class="space-y-1">
            <li v-for="[value, count] in sortedEntries(facets.tag)" :key="value">
              <button
                class="flex items-center justify-between w-full text-left text-sm px-2 py-1 rounded transition-colors"
                :class="filterTag === value
                  ? 'bg-accent-50 dark:bg-accent-900/20 text-accent-700 dark:text-accent-300 font-medium'
                  : 'text-slate-700 dark:text-slate-300 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated'"
                @click="toggleFacet('tag', value)"
              >
                <span>{{ value }}</span>
                <span class="text-xs text-slate-400">{{ count }}</span>
              </button>
            </li>
          </ul>
        </div>
      </aside>

      <!-- Results -->
      <main class="flex-1 min-w-0">
        <div class="flex items-center justify-between mb-4">
          <p class="text-sm text-slate-500 dark:text-slate-400">
            <span v-if="isLoading">Searching...</span>
            <span v-else>{{ total }} result{{ total !== 1 ? 's' : '' }}</span>
          </p>
        </div>

        <div v-if="results.length === 0 && !isLoading" class="text-center py-12">
          <p class="text-slate-500 dark:text-slate-400">
            {{ query || filterStatus || filterTeam || filterTag || filterRepo ? 'No results match your filters.' : 'Enter a search query or select a filter to get started.' }}
          </p>
        </div>

        <div v-else class="space-y-2">
          <button
            v-for="r in results"
            :key="`${r.repo_full_name}/${r.file_path}`"
            class="w-full text-left p-4 rounded-lg border border-border-light dark:border-slate-700 hover:bg-surface-light-alt dark:hover:bg-surface-elevated transition-colors"
            @click="navigate(r)"
          >
            <div class="flex items-center gap-2 mb-1">
              <span class="font-medium text-slate-800 dark:text-slate-200">{{ r.title }}</span>
              <span v-if="r.doc_type !== 'spec'" class="text-xs px-1.5 py-0.5 rounded bg-surface-light-elevated dark:bg-slate-700 text-slate-500">{{ r.doc_type }}</span>
              <StatusBadge :status="r.status" />
            </div>
            <div class="flex items-center gap-3 text-xs text-slate-500 mb-1">
              <span>{{ r.repo_full_name }}</span>
              <span v-if="r.team">{{ r.team }}</span>
              <span v-if="r.owner">by {{ r.owner }}</span>
            </div>
            <div v-if="r.heading" class="text-xs text-slate-400">{{ r.heading }}</div>
            <p v-if="r.snippet" class="text-sm text-slate-600 dark:text-slate-400 mt-1 line-clamp-2">{{ r.snippet }}</p>
            <div v-if="r.tags.length" class="flex gap-1 mt-2">
              <span v-for="tag in r.tags" :key="tag" class="text-xs px-1.5 py-0.5 rounded bg-surface-light-elevated dark:bg-slate-700 text-slate-500">{{ tag }}</span>
            </div>
          </button>
        </div>

        <!-- Pagination -->
        <div v-if="totalPages > 1" class="flex items-center justify-center gap-2 mt-6">
          <button
            class="px-3 py-1.5 text-sm rounded border border-border-light dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed"
            :disabled="page <= 1"
            @click="page--"
          >
            Previous
          </button>
          <span class="text-sm text-slate-500 dark:text-slate-400">
            Page {{ page }} of {{ totalPages }}
          </span>
          <button
            class="px-3 py-1.5 text-sm rounded border border-border-light dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:bg-surface-light-elevated dark:hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed"
            :disabled="page >= totalPages"
            @click="page++"
          >
            Next
          </button>
        </div>
      </main>
    </div>
  </div>
</template>
