<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useDocumentsStore } from '@/stores/documents'
import type { SearchResult } from '@/types'

const props = defineProps<{
  show: boolean
}>()

const emit = defineEmits<{
  close: []
}>()

const router = useRouter()
const documentsStore = useDocumentsStore()

const query = ref('')
const results = ref<SearchResult[]>([])
const selectedIndex = ref(0)
const isLoading = ref(false)
const inputRef = ref<HTMLInputElement | null>(null)
const listRef = ref<HTMLUListElement | null>(null)

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

watch(() => props.show, async (val) => {
  if (val) {
    query.value = ''
    results.value = []
    selectedIndex.value = 0
    await nextTick()
    inputRef.value?.focus()
  }
})

watch(query, (q) => {
  if (debounceTimer) clearTimeout(debounceTimer)
  if (!q.trim()) {
    results.value = []
    return
  }
  debounceTimer = setTimeout(() => {
    performSearch(q)
  }, 150)
})

async function performSearch(q: string) {
  if (!q.trim()) return
  isLoading.value = true
  try {
    const response = await documentsStore.search(q, 'all', 10)
    results.value = response.results
    selectedIndex.value = 0
  } catch (e) {
    console.error('Search failed:', e)
    results.value = []
  } finally {
    isLoading.value = false
  }
}

function handleKeydown(e: KeyboardEvent) {
  if (e.key === 'ArrowDown') {
    e.preventDefault()
    selectedIndex.value = Math.min(selectedIndex.value + 1, results.value.length - 1)
    scrollToSelected()
  } else if (e.key === 'ArrowUp') {
    e.preventDefault()
    selectedIndex.value = Math.max(selectedIndex.value - 1, 0)
    scrollToSelected()
  } else if (e.key === 'Enter') {
    e.preventDefault()
    if (results.value[selectedIndex.value]) {
      selectResult(results.value[selectedIndex.value])
    }
  } else if (e.key === 'Escape') {
    emit('close')
  }
}

function scrollToSelected() {
  nextTick(() => {
    const item = listRef.value?.children[selectedIndex.value] as HTMLElement
    item?.scrollIntoView({ block: 'nearest' })
  })
}

function selectResult(result: SearchResult) {
  if (result.type === 'document') {
    router.push(`/documents/${result.id}`)
  } else if (result.type === 'project') {
    router.push(`/projects/${result.id}`)
  }
  emit('close')
}

function getIcon(type: string): string {
  if (type === 'document') return '📄'
  if (type === 'project') return '📁'
  return '📄'
}
</script>

<template>
  <Teleport to="body">
    <Transition name="quick-switcher">
      <div v-if="show" class="quick-switcher" @click.self="emit('close')">
        <div class="quick-switcher__dialog">
          <div class="quick-switcher__input-wrap">
            <svg class="quick-switcher__icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="11" cy="11" r="8"/>
              <path d="m21 21-4.35-4.35"/>
            </svg>
            <input
              ref="inputRef"
              v-model="query"
              type="text"
              class="quick-switcher__input"
              placeholder="Search documents and projects..."
              @keydown="handleKeydown"
            />
            <kbd class="quick-switcher__kbd">Esc</kbd>
          </div>

          <div v-if="isLoading" class="quick-switcher__loading">
            <div class="quick-switcher__spinner"></div>
            Searching...
          </div>

          <ul v-else-if="results.length > 0" ref="listRef" class="quick-switcher__results">
            <li
              v-for="(result, index) in results"
              :key="result.id"
              :class="['quick-switcher__result', { 'quick-switcher__result--selected': index === selectedIndex }]"
              @click="selectResult(result)"
              @mouseenter="selectedIndex = index"
            >
              <span class="quick-switcher__result-icon">{{ getIcon(result.type) }}</span>
              <div class="quick-switcher__result-info">
                <span class="quick-switcher__result-title" v-html="result.highlight || result.title"></span>
                <span v-if="result.subtitle" class="quick-switcher__result-subtitle">{{ result.subtitle }}</span>
              </div>
              <span class="quick-switcher__result-type">{{ result.type }}</span>
            </li>
          </ul>

          <div v-else-if="query.trim()" class="quick-switcher__empty">
            No results found
          </div>

          <div v-else class="quick-switcher__hint">
            <p>Start typing to search...</p>
            <div class="quick-switcher__shortcuts">
              <span><kbd>↑</kbd><kbd>↓</kbd> Navigate</span>
              <span><kbd>Enter</kbd> Open</span>
              <span><kbd>Esc</kbd> Close</span>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
.quick-switcher {
  position: fixed;
  inset: 0;
  z-index: 2000;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 15vh;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.quick-switcher__dialog {
  width: 90%;
  max-width: 600px;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.quick-switcher__input-wrap {
  display: flex;
  align-items: center;
  padding: 0 1rem;
  border-bottom: 1px solid var(--border);
  gap: 0.75rem;
}

.quick-switcher__icon {
  flex-shrink: 0;
  color: var(--text-secondary);
}

.quick-switcher__input {
  flex: 1;
  padding: 1rem 0;
  background: none;
  border: none;
  font-size: 1rem;
  color: var(--text-primary);
  outline: none;
}

.quick-switcher__input::placeholder {
  color: var(--text-secondary);
}

.quick-switcher__kbd {
  padding: 0.25rem 0.5rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 4px;
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.quick-switcher__loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  padding: 2rem;
  color: var(--text-secondary);
  font-size: 0.875rem;
}

.quick-switcher__spinner {
  width: 18px;
  height: 18px;
  border: 2px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.6s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.quick-switcher__results {
  list-style: none;
  max-height: 400px;
  overflow-y: auto;
  padding: 0.5rem;
}

.quick-switcher__result {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.625rem 0.75rem;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.1s;
}

.quick-switcher__result--selected {
  background: var(--bg-secondary);
}

.quick-switcher__result-icon {
  font-size: 1.125rem;
  flex-shrink: 0;
}

.quick-switcher__result-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
}

.quick-switcher__result-title {
  font-size: 0.9375rem;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.quick-switcher__result-subtitle {
  font-size: 0.8125rem;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.quick-switcher__result-type {
  font-size: 0.75rem;
  padding: 0.125rem 0.5rem;
  background: var(--bg-tertiary);
  border-radius: 4px;
  color: var(--text-secondary);
  text-transform: capitalize;
  flex-shrink: 0;
}

.quick-switcher__empty {
  padding: 2rem;
  text-align: center;
  color: var(--text-secondary);
  font-size: 0.875rem;
}

.quick-switcher__hint {
  padding: 1.5rem;
  text-align: center;
  color: var(--text-secondary);
  font-size: 0.875rem;
}

.quick-switcher__shortcuts {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
  margin-top: 1rem;
  font-size: 0.8125rem;
}

.quick-switcher__shortcuts kbd {
  padding: 0.125rem 0.375rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 4px;
  font-size: 0.75rem;
  margin-right: 0.25rem;
}

/* Transitions */
.quick-switcher-enter-active,
.quick-switcher-leave-active {
  transition: opacity 0.15s ease;
}

.quick-switcher-enter-active .quick-switcher__dialog,
.quick-switcher-leave-active .quick-switcher__dialog {
  transition: transform 0.15s ease, opacity 0.15s ease;
}

.quick-switcher-enter-from,
.quick-switcher-leave-to {
  opacity: 0;
}

.quick-switcher-enter-from .quick-switcher__dialog,
.quick-switcher-leave-to .quick-switcher__dialog {
  transform: scale(0.95) translateY(-10px);
  opacity: 0;
}
</style>
