<template>
  <div class="space-y-6">
    <h2 class="text-2xl font-bold">影片搜尋</h2>
    
    <!-- Search Form -->
    <div class="bg-gray-800 rounded-lg p-6 border border-gray-700">
      <div class="flex space-x-4 mb-4">
        <input
          v-model="searchQuery"
          @keyup.enter="performSearch"
          type="text"
          placeholder="輸入搜尋關鍵字..."
          class="flex-1 bg-gray-700 border border-gray-600 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-blue-500"
        />
        <button
          @click="performSearch"
          :disabled="loading"
          class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 px-6 py-3 rounded-lg font-semibold transition"
        >
          {{ loading ? '搜尋中...' : '搜尋' }}
        </button>
      </div>
      <!-- Mode Selector -->
      <div class="flex items-center space-x-4">
        <span class="text-gray-400 text-sm">搜尋模式:</span>
        <select
          v-model="searchMode"
          class="bg-gray-700 border border-gray-600 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
        >
          <option value="vector">向量搜尋 (Vector)</option>
          <option value="bm25">關鍵字搜尋 (BM25)</option>
          <option value="hybrid">混合搜尋 (Hybrid)</option>
          <option value="smart">智慧搜尋 (Smart)</option>
        </select>
        <span class="text-gray-500 text-xs">
          {{ modeDescription }}
        </span>
      </div>
    </div>

    <!-- Results -->
    <div v-if="results.length > 0" class="space-y-4">
      <h3 class="text-xl font-semibold">搜尋結果 ({{ results.length }})</h3>
      <div class="grid gap-4">
        <div
          v-for="(hit, index) in results"
          :key="index"
          @click="goToDetail(hit.vid, hit.id)"
          class="bg-gray-800 rounded-lg p-6 border border-gray-700 hover:border-blue-500 cursor-pointer transition"
        >
          <div class="flex justify-between items-start">
            <div class="flex-1">
              <div class="flex items-center space-x-3 mb-2">
                <span class="text-gray-400 text-sm">
                  type: <span class="text-blue-300">{{ hit.id.split('_')[0] }}</span>
                  uuid: <span class="text-purple-300">{{ hit.vid }}</span>
                </span>
                <!-- Parent ID Badge -->
                <span v-if="hit.parent_id" class="bg-yellow-900 text-yellow-300 px-2 py-1 rounded text-sm">
                  parent_id: {{ hit.parent_id }}
                </span>
                <!-- Visual Stats Badge -->
                <span v-if="hit.has_visual_stats" class="bg-cyan-900 text-cyan-300 px-2 py-1 rounded text-sm">
                  📦 Visual
                </span>
                <span v-else class="bg-gray-700 text-gray-400 px-2 py-1 rounded text-sm">
                  No Visual
                </span>
              </div>
              <p class="text-lg mb-3">{{ hit.text }}</p>
              <!-- Frame Range (精確定位) -->
              <div class="bg-gray-900 p-2 rounded mb-2 text-sm">
                <span class="text-gray-500">Frame:</span>
                <span class="text-white font-mono ml-2">{{ hit.start_frame }}</span>
                <span class="text-gray-600 mx-1">→</span>
                <span class="text-white font-mono">{{ hit.end_frame }}</span>
                <span class="text-gray-500 ml-2">({{ hit.fps.toFixed(2) }} fps)</span>
              </div>
              <!-- Time (參考) -->
              <div class="flex space-x-6 text-sm text-gray-400">
                <span>時間: {{ hit.start.toFixed(2) }}s → {{ hit.end.toFixed(2) }}s</span>
                <span>分數: {{ hit.score.toFixed(3) }}</span>
              </div>
              <div v-if="hit.title || hit.file_path" class="mt-2 text-sm text-gray-500 space-y-1">
                <div v-if="hit.title">標題: {{ hit.title }}</div>
                <div v-if="hit.file_path">檔案: {{ hit.file_path.split('/').pop() }}</div>
              </div>
            </div>
            <div class="text-right">
              <div class="text-2xl font-bold text-blue-400">
                {{ (hit.score * 100).toFixed(1) }}%
              </div>
              <div class="text-sm text-gray-500">匹配度</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- No Results -->
    <div v-else-if="searched && !loading" class="text-center py-12 text-gray-500">
      找不到符合的結果
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { searchVideos } from '@/api/client'

const router = useRouter()
const route = useRoute()

onMounted(() => {
  localStorage.removeItem('searchState')
  
  const q = route.query.q as string
  if (q) {
    searchQuery.value = q
    performSearch()
  }
})

interface SearchHit {
  id: string
  vid: string
  start_frame: number
  end_frame: number
  fps: number
  start: number
  end: number
  text: string
  score: number
  title?: string
  file_path?: string
  has_visual_stats?: boolean
  parent_id?: string
}

const searchQuery = ref('')
const searchMode = ref('vector')
const results = ref<SearchHit[]>([])
const loading = ref(false)
const searched = ref(false)

const modeDescription = computed(() => {
  const modes: Record<string, string> = {
    vector: '語意向量搜尋，使用 Qdrant 向量資料庫',
    bm25: '關鍵字搜尋，使用 PostgreSQL tsvector',
    hybrid: '混合搜尋，結合向量與關鍵字',
    smart: '智慧搜尋，使用 Gemma4 LLM 分析查詢'
  }
  return modes[searchMode.value] || ''
})

const performSearch = async () => {
  if (!searchQuery.value.trim()) return
  
  loading.value = true
  searched.value = true
  
  try {
    const result = await searchVideos(searchQuery.value, 20, searchMode.value)
    results.value = result.hits
  } catch (error) {
    console.error('Search failed:', error)
    alert('搜尋失敗: ' + error)
  } finally {
    loading.value = false
  }
}

const goToDetail = (uuid: string, chunkId: string) => {
  localStorage.setItem('searchState', JSON.stringify({ query: searchQuery.value, results: results.value }))
  router.push({
    name: 'chunk-detail',
    params: { uuid, chunkId }
  })
}
</script>
