<script setup lang="ts">
import { useDebounceFn } from '@vueuse/core'
import { useSearch, type SearchResult } from '~/composables/useSearch'
import { usePageNavigation } from '~/composables/usePageNavigation'
import { EditorBlock } from '@enesis/editor'

const open = defineModel<boolean>('open', { required: true })
const { navigateToBlock } = usePageNavigation()

const props = defineProps<{
  searchTrigger?: number
}>()

const tabs = [
  { label: 'References', icon: 'i-lucide-link', value: 'refs' },
  { label: 'Search', icon: 'i-lucide-search', value: 'search' },
]
const activeTab = ref('refs')

watch(() => props.searchTrigger, () => {
  activeTab.value = 'search'
})

const { searchBlocks, isModelLoading, isSearching } = useSearch()

const searchQuery = ref('')
const results = ref<SearchResult[]>([])

const debouncedSearch = useDebounceFn(async (query: string) => {
  if (!query.trim()) {
    results.value = []
    return
  }
  results.value = await searchBlocks(query)
}, 200)

watch(searchQuery, q => debouncedSearch(q))

// Map source type to design-system badge styles
const sourceBadge: Record<string, { label: string; class: string }> = {
  vector:  { label: 'semantic', class: 'bg-(--ui-primary)/10 text-(--ui-primary)' },
  keyword: { label: 'keyword',  class: 'bg-(--ui-border-accented) text-muted' },
  hybrid:  { label: 'hybrid',   class: 'bg-(--ui-secondary)/10 text-(--ui-secondary)' },
}

function handleResultClick(r: SearchResult) {
  open.value = false
  navigateToBlock(r.blockId)
}
</script>

<template>
  <USidebar
    v-model:open="open"
    collapsible="offcanvas"
    side="right"
    :ui="{ body: 'p-0' }"
    rail
  >
    <template #header>
      <UTabs
        v-model="activeTab"
        :items="tabs"
        :content="false"
        size="sm"
        color="neutral"
        variant="link"
        class="w-full"
      />
    </template>

    <!-- References tab -->
    <div v-if="activeTab === 'refs'" class="flex flex-col items-center justify-center h-full px-6 py-16 text-center gap-3">
      <div class="w-10 h-10 rounded-xl bg-(--ui-primary)/10 flex items-center justify-center">
        <UIcon name="i-lucide-link" class="w-5 h-5 text-(--ui-primary)" />
      </div>
      <p class="text-sm font-medium text-default">No references yet</p>
      <p class="text-xs text-muted leading-relaxed">
        Link to this page from your notes using <span class="font-mono text-xs bg-elevated px-1 py-0.5 rounded">[[page name]]</span> and references will appear here.
      </p>
    </div>

    <!-- Search tab -->
    <div v-else-if="activeTab === 'search'" class="flex flex-col h-full">

      <!-- Input -->
      <div class="shrink-0 p-3 pb-2">
        <UInput
          v-model="searchQuery"
          icon="i-lucide-search"
          placeholder="Search notes…"
          size="sm"
          color="neutral"
          :loading="isSearching"
          autofocus
          class="w-full"
        />
      </div>

      <!-- Model loading notice -->
      <div v-if="isModelLoading" class="shrink-0 mx-3 mb-2 px-3 py-2.5 rounded-lg bg-(--ui-primary)/5 border border-(--ui-primary)/15">
        <div class="flex items-center gap-2 mb-1.5">
          <UIcon name="i-lucide-loader" class="w-3.5 h-3.5 text-(--ui-primary) animate-spin shrink-0" />
          <span class="text-xs font-medium text-(--ui-primary)">Warming up search…</span>
        </div>
        <UProgress size="xs" color="primary" />
      </div>

      <!-- Results area -->
      <div class="flex-1 overflow-y-auto px-3 pb-3 space-y-1.5">

        <!-- Idle state -->
        <div v-if="!searchQuery.trim()" class="flex flex-col items-center justify-center py-16 gap-2 text-center">
          <UIcon name="i-lucide-search" class="w-6 h-6 text-muted/40" />
          <p class="text-sm text-muted">Type to search your notes</p>
        </div>

        <!-- No results -->
        <div
          v-else-if="results.length === 0 && !isSearching"
          class="flex flex-col items-center justify-center py-16 gap-2 text-center"
        >
          <UIcon name="i-lucide-file-search" class="w-6 h-6 text-muted/40" />
          <p class="text-sm text-muted">
            Nothing found for <span class="text-default italic">"{{ searchQuery }}"</span>
          </p>
        </div>

        <!-- Results -->
        <template v-else>
          <button
            v-for="r in results"
            :key="r.blockId"
            @click="handleResultClick(r)"
            class="group w-full text-left rounded-lg border border-default
                   hover:border-(--ui-primary)/30 hover:bg-elevated
                   transition-all duration-150 p-3
                   focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-(--ui-primary)"
          >
            <!-- Page title + source badge -->
            <div class="flex items-center justify-between gap-2 mb-1.5">
              <span class="text-xs font-medium text-muted truncate flex items-center gap-1.5">
                <UIcon name="i-lucide-file-text" class="w-3 h-3 shrink-0" />
                {{ r.pageTitle }}
              </span>
              <span
                class="shrink-0 text-[10px] font-medium uppercase tracking-wider rounded px-1.5 py-px"
                :class="sourceBadge[r.source]?.class ?? 'bg-elevated text-muted'"
              >
                {{ sourceBadge[r.source]?.label ?? r.source }}
              </span>
            </div>

            <!-- Block rendering (read-only ProseMirror with full markdown decorators) -->
            <div class="text-sm leading-relaxed text-default max-h-24 overflow-hidden">
              <EditorBlock
                :content="r.content"
                :readonly="true"
                marker-mode="always-visible"
              />
            </div>

            <!-- Path -->
            <p class="mt-2 text-[11px] text-muted/50 font-mono truncate
                       opacity-0 group-hover:opacity-100 transition-opacity duration-150">
              {{ r.pagePath }}
            </p>
          </button>
        </template>

      </div>
    </div>
  </USidebar>
</template>
