<template>
  <Teleport to="body">
    <Transition name="modal">
      <div v-if="visible" class="modal-overlay" @click.self="close">
        <div class="search-modal">
          <!-- 搜索输入 -->
          <div class="search-header">
            <Search :size="20" class="search-icon" />
            <input
                ref="inputRef"
                v-model="searchQuery"
                type="text"
                class="search-input"
                placeholder="搜索对话..."
                @keydown.escape="close"
                @keydown.down.prevent="navigateDown"
                @keydown.up.prevent="navigateUp"
                @keydown.enter="selectCurrent"
            />
            <kbd class="esc-hint">ESC</kbd>
          </div>

          <!-- 搜索结果 -->
          <div class="search-results">
            <div v-if="filteredConversations.length === 0" class="no-results">
              <FolderOpen :size="40" class="no-results-icon" />
              <p>没有找到相关对话</p>
            </div>

            <div
                v-for="(conv, index) in filteredConversations"
                :key="conv.id"
                class="result-item"
                :class="{ active: index === selectedIndex }"
                @click="selectConversation(conv.id)"
                @mouseenter="selectedIndex = index"
            >
              <MessageSquare :size="18" class="result-icon" />
              <div class="result-content">
                <div class="result-title">{{ conv.title }}</div>
                <div class="result-meta">
                  <span>{{ conv.messages.length }} 条消息</span>
                  <span class="dot">·</span>
                  <span>{{ formatTime(conv.updatedAt) }}</span>
                </div>
              </div>
              <Pin v-if="conv.pinned" :size="14" class="pin-icon" />
            </div>
          </div>

          <!-- 底部提示 -->
          <div class="search-footer">
            <div class="hint">
              <kbd>↑↓</kbd>
              <span>导航</span>
            </div>
            <div class="hint">
              <kbd>↵</kbd>
              <span>选择</span>
            </div>
            <div class="hint">
              <kbd>ESC</kbd>
              <span>关闭</span>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '@/stores/chat'
import { useSettingsStore } from '@/stores/settings'
import { Search, MessageSquare, FolderOpen, Pin } from '@/components/icons'
import { formatTimestamp } from '@/utils/helpers'

const chatStore = useChatStore()
const settingsStore = useSettingsStore()

const { conversations } = storeToRefs(chatStore)
const { showSearchModal: visible } = storeToRefs(settingsStore)

const searchQuery = ref('')
const selectedIndex = ref(0)
const inputRef = ref<HTMLInputElement | null>(null)

const filteredConversations = computed(() => {
  if (!searchQuery.value.trim()) {
    return conversations.value.slice(0, 10)
  }

  const query = searchQuery.value.toLowerCase()
  return conversations.value.filter(conv => {
    // 搜索标题
    if (conv.title.toLowerCase().includes(query)) return true

    // 搜索消息内容
    return conv.messages.some(msg =>
        msg.content.text?.toLowerCase().includes(query)
    )
  }).slice(0, 10)
})

function formatTime(timestamp: number) {
  return formatTimestamp(timestamp)
}

function close() {
  settingsStore.closeSearchModal()
  searchQuery.value = ''
  selectedIndex.value = 0
}

function navigateDown() {
  if (selectedIndex.value < filteredConversations.value.length - 1) {
    selectedIndex.value++
  }
}

function navigateUp() {
  if (selectedIndex.value > 0) {
    selectedIndex.value--
  }
}

function selectCurrent() {
  const conv = filteredConversations.value[selectedIndex.value]
  if (conv) {
    selectConversation(conv.id)
  }
}

function selectConversation(id: string) {
  chatStore.selectConversation(id)
  close()
}

// 打开时聚焦输入框
watch(visible, (val) => {
  if (val) {
    nextTick(() => {
      inputRef.value?.focus()
    })
  }
})

// 搜索内容变化时重置选中索引
watch(searchQuery, () => {
  selectedIndex.value = 0
})
</script>

<style lang="scss" scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 100px;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.search-modal {
  width: 560px;
  max-height: 480px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .dark & {
    background: #1e1e2e;
  }
}

.search-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;

  .dark & {
    border-bottom-color: #2d2d3d;
  }
}

.search-icon {
  color: #9ca3af;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  color: #1f2937;
  background: transparent;

  .dark & {
    color: #f3f4f6;
  }

  &::placeholder {
    color: #9ca3af;
  }
}

.esc-hint {
  font-size: 11px;
  padding: 4px 8px;
  border-radius: 4px;
  background: #f3f4f6;
  color: #6b7280;

  .dark & {
    background: #374151;
    color: #9ca3af;
  }
}

.search-results {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #9ca3af;

  .no-results-icon {
    margin-bottom: 12px;
    opacity: 0.5;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

.result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 10px;
  cursor: pointer;
  transition: background 0.15s ease;

  &:hover,
  &.active {
    background: #f3f4f6;

    .dark & {
      background: #2d2d3d;
    }
  }
}

.result-icon {
  color: #6b7280;
  flex-shrink: 0;
}

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

.result-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  .dark & {
    color: #f3f4f6;
  }
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 2px;
  font-size: 12px;
  color: #9ca3af;

  .dot {
    opacity: 0.5;
  }
}

.pin-icon {
  color: #f59e0b;
  flex-shrink: 0;
}

.search-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;
  padding: 12px 20px;
  border-top: 1px solid #e2e8f0;
  background: #f8fafc;

  .dark & {
    border-top-color: #2d2d3d;
    background: #181825;
  }
}

.hint {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #9ca3af;

  kbd {
    padding: 2px 6px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

    .dark & {
      background: #374151;
    }
  }
}

// 过渡动画
.modal-enter-active,
.modal-leave-active {
  transition: all 0.2s ease;

  .search-modal {
    transition: all 0.2s ease;
  }
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;

  .search-modal {
    transform: scale(0.95) translateY(-20px);
    opacity: 0;
  }
}
</style>