<template>
  <div class="awesome-bar-dropdown" v-show="show && hasResults">
    <div class="search-results-container">
      <!-- Loading state -->
      <div v-if="isLoading" class="loading-state">
        <n-spin size="small" />
        <span class="loading-text">{{ t('Searching...') }}</span>
      </div>

      <!-- Results -->
      <div v-else class="results-wrapper">
        <div
          v-for="(resultSet, setIndex) in filteredResults"
          :key="setIndex"
          class="result-set"
        >
          <div class="result-set-title" v-if="resultSet.results.length > 0">
            {{ t(resultSet.title) }}
          </div>
          
          <div class="result-items">
            <div
              v-for="(result, resultIndex) in resultSet.results.slice(0, 5)"
              :key="resultIndex"
              class="result-item"
              :class="{ active: activeIndex === `${setIndex}-${resultIndex}` }"
              @click="handleResultClick(result)"
              @mouseenter="activeIndex = `${setIndex}-${resultIndex}`"
            >
              <div class="result-icon">
                <img
                  v-if="result.image"
                  :src="result.image"
                  class="result-image"
                  @error="handleImageError"
                />
                <Icon v-else :icon="getResultIcon(result.type)" class="type-icon" />
              </div>
              
              <div class="result-content">
                <div class="result-label" v-html="result.label"></div>
                <div class="result-description" v-if="result.description" v-html="truncateDescription(result.description)"></div>
              </div>
              
              <div class="result-badge" v-if="result.recent">
                <n-tag size="tiny" type="info">{{ t('Recent') }}</n-tag>
              </div>
              
              <div class="result-type-badge">
                <span class="type-text">{{ result.type }}</span>
              </div>
            </div>
          </div>
          
          <!-- Show more button for global results -->
          <div
            v-if="resultSet.fetch_type === 'Global' && resultSet.results.length > 5"
            class="show-more"
            @click="showAllResults(resultSet)"
          >
            {{ t('Show {0} more results', [resultSet.results.length - 5]) }}
          </div>
        </div>
      </div>

      <!-- Empty state -->
      <div v-if="!isLoading && !hasResults" class="empty-state">
        <Icon icon="tabler:search-off" class="empty-icon" />
        <div class="empty-text">{{ t('No results found') }}</div>
      </div>

      <!-- Footer tips -->
      <div class="search-footer" v-if="hasResults && !isLoading">
        <div class="search-tips">
          <span class="tip-item">
            <kbd>↑↓</kbd> {{ t('Navigate') }}
          </span>
          <span class="tip-item">
            <kbd>↵</kbd> {{ t('Select') }}
          </span>
          <span class="tip-item">
            <kbd>Esc</kbd> {{ t('Close') }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NSpin, NTag } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '../i18n'
import { useRouter } from 'vue-router'

interface SearchResult {
  type: string
  label: string
  value: string
  description?: string
  route?: any[]
  onclick?: () => void
  index: number
  match?: string
  image?: string
  recent?: boolean
}

interface SearchResultSet {
  title: string
  results: SearchResult[]
  fetch_type: 'Nav' | 'Global'
}

const props = defineProps<{
  show: boolean
  isLoading: boolean
  results: SearchResultSet[]
}>()

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

const router = useRouter()
const activeIndex = ref<string>('')

const filteredResults = computed(() => {
  return props.results.filter(set => set.results.length > 0)
})

const hasResults = computed(() => {
  return filteredResults.value.some(set => set.results.length > 0)
})

// Get icon based on result type
function getResultIcon(type: string): string {
  const iconMap: Record<string, string> = {
    'Recent': 'tabler:clock',
    'List': 'tabler:list',
    'New': 'tabler:plus',
    'Document': 'tabler:file-text',
    'Workspace': 'tabler:layout-dashboard',
    'Report': 'tabler:chart-bar',
    'Page': 'tabler:file',
    'Dashboard': 'tabler:dashboard',
    'Form': 'tabler:forms'
  }
  
  return iconMap[type] || 'tabler:circle'
}

// Handle result click
function handleResultClick(result: SearchResult) {
  emit('select', result)
}

// Show all results
function showAllResults(resultSet: SearchResultSet) {
  // Navigate to search results page
  if (resultSet.results.length > 0) {
    const firstResult = resultSet.results[0]
    router.push({
      name: 'SearchResults',
      query: { q: firstResult.match || firstResult.value }
    })
    emit('close')
  }
}

// Truncate description
function truncateDescription(description: string): string {
  const maxLength = 80
  if (!description) return ''
  if (description.length <= maxLength) return description
  return description.substring(0, maxLength) + '...'
}

// Handle image error
function handleImageError(event: Event) {
  const target = event.target as HTMLImageElement
  target.style.display = 'none'
}

// Keyboard navigation
watch(() => props.show, (newShow) => {
  if (newShow) {
    // Reset active index when dropdown opens
    if (filteredResults.value.length > 0 && filteredResults.value[0].results.length > 0) {
      activeIndex.value = '0-0'
    }
  }
})
</script>

<style scoped>
.awesome-bar-dropdown {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  max-height: 500px;
  overflow: hidden;
  z-index: 1000;
  min-width: 500px;
}

.search-results-container {
  display: flex;
  flex-direction: column;
  max-height: 500px;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 24px;
  color: #6b7280;
}

.loading-text {
  font-size: 14px;
}

.results-wrapper {
  overflow-y: auto;
  max-height: 450px;
}

.result-set {
  border-bottom: 1px solid #f3f4f6;
}

.result-set:last-child {
  border-bottom: none;
}

.result-set-title {
  padding: 8px 16px;
  font-size: 12px;
  font-weight: 600;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  background: #f9fafb;
  border-bottom: 1px solid #f3f4f6;
}

.result-items {
  /* No padding, items have their own */
}

.result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 16px;
  cursor: pointer;
  transition: all 0.15s ease;
  border-left: 3px solid transparent;
}

.result-item:hover,
.result-item.active {
  background: #f0f9ff;
  border-left-color: #3b82f6;
}

.result-icon {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  background: #f3f4f6;
}

.result-image {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  object-fit: cover;
}

.type-icon {
  font-size: 18px;
  color: #6b7280;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-label {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-label :deep(mark) {
  background: #fef3c7;
  color: #92400e;
  font-weight: 600;
  padding: 0 2px;
  border-radius: 2px;
}

.result-description {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-description :deep(mark) {
  background: #fef3c7;
  color: #92400e;
}

.result-badge {
  flex-shrink: 0;
}

.result-type-badge {
  flex-shrink: 0;
  font-size: 11px;
  color: #9ca3af;
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.show-more {
  padding: 10px 16px;
  text-align: center;
  font-size: 13px;
  color: #3b82f6;
  cursor: pointer;
  background: #f9fafb;
  border-top: 1px solid #f3f4f6;
  transition: background 0.15s ease;
}

.show-more:hover {
  background: #f0f9ff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  color: #9ca3af;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-text {
  font-size: 14px;
}

.search-footer {
  border-top: 1px solid #e5e7eb;
  padding: 8px 16px;
  background: #f9fafb;
}

.search-tips {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #6b7280;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.tip-item kbd {
  display: inline-block;
  padding: 2px 6px;
  font-size: 11px;
  line-height: 1.4;
  color: #374151;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  font-family: monospace;
}

/* Scrollbar styles */
.results-wrapper::-webkit-scrollbar {
  width: 6px;
}

.results-wrapper::-webkit-scrollbar-track {
  background: #f9fafb;
}

.results-wrapper::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.results-wrapper::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

/* Responsive */
@media (max-width: 768px) {
  .awesome-bar-dropdown {
    min-width: auto;
    left: -12px;
    right: -12px;
  }
  
  .result-item {
    padding: 12px;
  }
  
  .search-tips {
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>
