<template>
  <div class="icon-picker">
    <!-- 触发按钮 -->
    <n-button 
      @click="openPicker" 
      :type="(selectedIcon ? 'default' : 'dashed') as any"
      class="icon-trigger"
      block
    >
      <template v-if="selectedIcon">
        <Icon :icon="selectedIcon" :width="20" :height="20" style="margin-right: 8px;" />
        {{ getDisplayName(selectedIcon) }}
      </template>
      <template v-else>
        <Icon :icon="`${currentLibraryConfig.prefix}:menu`" :width="20" :height="20" style="margin-right: 8px;" />
        {{ t('Select Icon') }}
      </template>
    </n-button>

    <!-- 图标选择弹窗 -->
    <n-modal
      v-model:show="showPicker"
      preset="dialog"
      :title="t('Select Icon')"
      :positive-text="t('Confirm')"
      :negative-text="t('Cancel')"
      @positive-click="confirmSelection"
      @negative-click="cancelSelection"
      size="huge"
      :bordered="false"
      style="width: 90vw; max-width: 1200px;"
    >
      <div class="icon-picker-content">
        <!-- 搜索栏和图标库选择 -->
        <div class="search-section">
          <div class="search-controls">
            <n-input
              v-model:value="searchQuery"
              :placeholder="t('Search icon name...')"
              clearable
              size="large"
              @update:value="handleSearch"
              style="flex: 1;"
            >
              <template #prefix>
                <Icon :icon="`${currentLibraryConfig.prefix}:search`" />
              </template>
            </n-input>
            <n-select
              v-model:value="currentLibrary"
              :options="libraryOptions"
              :placeholder="t('Icon Library')"
              size="large"
              style="width: 200px; margin-left: 12px;"
              @update:value="handleLibraryChange"
            />
          </div>
          <div class="icon-count">
            {{ t('Total') }} {{ filteredIcons.length }} {{ t('icons') }} ({{ currentLibraryConfig.displayName }})
            <span v-if="loading" class="loading-text">{{ t('Loading...') }}</span>
          </div>
        </div>

        <!-- 图标网格 -->
        <div class="icon-grid" @scroll="handleScroll">
          <div 
            v-for="icon in displayedIcons" 
            :key="icon"
            class="icon-item"
            :class="{ active: tempSelectedIcon === icon }"
            @click="selectIcon(icon)"
            :title="icon"
          >
            <!-- 复制按钮 -->
            <button 
              class="copy-button"
              @click.stop="copyIconName(icon)"
              :title="t('Copy icon name')"
            >
              {{ t('Copy') }}
            </button>
            
            <div class="icon-wrapper">
              <Icon 
                :icon="currentLibraryConfig.name === 'all' ? icon : `${currentLibraryConfig.prefix}:${icon}`" 
                :width="32" 
                :height="32"
                @error="handleIconError"
              />
            </div>
            <div class="icon-name">{{ currentLibraryConfig.name === 'all' ? icon.split(':')[1] || icon : icon }}</div>
          </div>
          
          <!-- 加载更多按钮 -->
          <div v-if="hasMoreIcons && !loading" class="load-more" @click="loadMoreIcons">
            <Icon :icon="`${currentLibraryConfig.prefix}:plus`" :width="24" :height="24" />
            <span>{{ t('Load More') }}</span>
          </div>
          
          <!-- 加载中状态 -->
          <div v-if="loading" class="loading-more">
            <Icon :icon="`${currentLibraryConfig.prefix}:loader`" :width="24" :height="24" class="spinning" />
            <span>{{ t('Loading...') }}</span>
          </div>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { NButton, NModal, NInput, NSelect, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { getIconLibraryConfig, getAvailableIconLibraries, DEFAULT_ICON_LIBRARY } from '@/shared/utils/icon-libraries'
import { t } from '@/shared/i18n'

interface Props {
  modelValue?: string
  iconLibrary?: string // 图标库名称，默认为 DEFAULT_ICON_LIBRARY
}

interface Emits {
  (e: 'update:modelValue', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  iconLibrary: DEFAULT_ICON_LIBRARY
})

const emit = defineEmits<Emits>()

// 消息提示
const message = useMessage()

// 响应式数据
const showPicker = ref(false)
const searchQuery = ref('')
const selectedIcon = ref(props.modelValue || '')
const tempSelectedIcon = ref('')
const allIcons = ref<string[]>([])
const currentLibrary = ref(props.iconLibrary || DEFAULT_ICON_LIBRARY)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(200) // 每页200个图标
const hasMore = ref(true)

// 计算属性
const currentLibraryConfig = computed(() => {
  return getIconLibraryConfig(currentLibrary.value) || getIconLibraryConfig(DEFAULT_ICON_LIBRARY)!
})

const libraryOptions = computed(() => {
  return getAvailableIconLibraries().map(lib => ({
    label: lib.displayName,
    value: lib.name,
    description: lib.description
  }))
})

const filteredIcons = computed(() => {
  if (!searchQuery.value) {
    return allIcons.value
  }
  const query = searchQuery.value.toLowerCase()
  return allIcons.value.filter(icon => 
    icon.toLowerCase().includes(query)
  )
})

// 当前显示的图标（分页）
const displayedIcons = computed(() => {
  const filtered = filteredIcons.value
  const startIndex = 0
  const endIndex = currentPage.value * pageSize.value
  return filtered.slice(startIndex, endIndex)
})

// 是否还有更多图标
const hasMoreIcons = computed(() => {
  return displayedIcons.value.length < filteredIcons.value.length
})

// 加载指定图标库的所有图标（优化版）
async function loadAllIcons() {
  loading.value = true
  try {
    if (currentLibraryConfig.value.name === 'all') {
      await loadAllIconsFromAllLibraries()
    } else {
      const config = currentLibraryConfig.value
      const response = await fetch(config.apiUrl)
      const data = await response.json()
      
      if (data && data.uncategorized) {
        allIcons.value = data.uncategorized.sort()
      } else if (data && data.categories) {
        // 处理分类结构的图标库（如Carbon Icons）
        const allCategoryIcons: string[] = []
        Object.values(data.categories).forEach((categoryIcons: any) => {
          if (Array.isArray(categoryIcons)) {
            allCategoryIcons.push(...categoryIcons)
          }
        })
        allIcons.value = allCategoryIcons.sort()
      } else {
        // 如果API失败，使用预定义的常用图标列表
        allIcons.value = getFallbackIcons(config.prefix)
      }
      
      // 重置分页
      currentPage.value = 1
      hasMore.value = true
    }
  } catch (error) {
    console.warn(`Failed to load icons from ${currentLibraryConfig.value.displayName} API, using fallback list:`, error)
    // 使用预定义的图标列表作为后备
    allIcons.value = getFallbackIcons(currentLibraryConfig.value.prefix)
    currentPage.value = 1
    hasMore.value = true
  } finally {
    loading.value = false
  }
}

// 从所有图标库加载图标
async function loadAllIconsFromAllLibraries() {
  try {
    const availableLibraries = getAvailableIconLibraries().filter(lib => lib.name !== 'all')
    
    // 并行加载所有图标库
    const promises = availableLibraries.map(async (library) => {
      try {
        const response = await fetch(library.apiUrl)
        const data = await response.json()
        
        let icons: string[] = []
        if (data && data.uncategorized) {
          icons = data.uncategorized
        } else if (data && data.categories) {
          // 处理分类结构
          Object.values(data.categories).forEach((categoryIcons: any) => {
            if (Array.isArray(categoryIcons)) {
              icons.push(...categoryIcons)
            }
          })
        }
        
        // 为每个图标添加库前缀信息
        return icons.map(icon => ({
          name: icon,
          library: library.prefix,
          fullName: `${library.prefix}:${icon}`
        }))
      } catch (error) {
        console.warn(`Failed to load icons from ${library.displayName}:`, error)
        return []
      }
    })
    
    const results = await Promise.all(promises)
    const allIconsWithLibrary = results.flat()
    
    // 转换为字符串数组，格式为 "library:icon"
    allIcons.value = allIconsWithLibrary.map(item => item.fullName).sort()
    
    // 重置分页
    currentPage.value = 1
    hasMore.value = true
  } catch (error) {
    console.error('Failed to load all icons:', error)
    // 使用fallback
    allIcons.value = getFallbackIcons('all')
    currentPage.value = 1
    hasMore.value = true
  }
}

// 加载更多图标
function loadMoreIcons() {
  if (hasMoreIcons.value && !loading.value) {
    currentPage.value++
  }
}

// 获取后备图标列表
function getFallbackIcons(_prefix: string): string[] {
  const commonIcons = [
    'home', 'settings', 'user', 'menu', 'search', 'file', 'folder', 'dashboard',
    'users', 'lock', 'key', 'shield', 'crown', 'trophy', 'gift', 'heart', 'star',
    'download', 'upload', 'printer', 'file-text', 'chart-bar', 'chart-pie', 'chart-line',
    'table', 'database', 'cloud', 'api', 'tool', 'bug', 'code', 'flask', 'bulb',
    'camera', 'photo', 'video', 'music', 'volume', 'arrow-up', 'arrow-down',
    'arrow-left', 'arrow-right', 'edit', 'trash', 'plus', 'minus', 'check', 'x',
    'mail', 'phone', 'message', 'bell', 'shopping-cart', 'currency-dollar',
    'credit-card', 'book', 'school', 'info-circle', 'alert-circle', 'robot',
    'clock', 'calendar', 'map', 'globe', 'wifi', 'bluetooth', 'battery'
  ]
  
  return commonIcons.sort()
}

// 选择图标
function selectIcon(iconName: string) {
  tempSelectedIcon.value = iconName
}

// 打开弹窗时初始化临时选择
async function openPicker() {
  // 如果已有图标名称包含前缀，提取图标名称部分
  if (selectedIcon.value && selectedIcon.value.includes(':')) {
    const [prefix, iconName] = selectedIcon.value.split(':')
    
    // 查找对应的图标库
    const correctLibrary = getIconLibraryConfig(prefix)
    if (correctLibrary) {
      // 切换到对应的图标库
      currentLibrary.value = correctLibrary.name
      // 切换库后重新加载图标数据
      await loadAllIcons()
      // 设置临时选择的图标名称（不包含前缀）
      tempSelectedIcon.value = iconName
      // 自动设置搜索关键词为图标名称，显示相关搜索结果
      searchQuery.value = iconName
    } else {
      // 如果找不到对应的库，保持在All选项
      if (currentLibraryConfig.value.name !== 'all') {
        currentLibrary.value = 'all'
        await loadAllIcons()
      }
      tempSelectedIcon.value = selectedIcon.value
      // 在All选项中，使用完整图标名称作为搜索关键词
      searchQuery.value = selectedIcon.value
    }
  } else if (selectedIcon.value) {
    // 没有前缀的图标，保持当前库设置，但设置搜索关键词
    tempSelectedIcon.value = selectedIcon.value
    searchQuery.value = selectedIcon.value
  } else {
    // 没有图标，清空搜索
    tempSelectedIcon.value = ''
    searchQuery.value = ''
  }
  showPicker.value = true
}

// 确认选择
function confirmSelection() {
  // 保存完整的图标名称（包含前缀）
  let fullIconName: string
  if (currentLibraryConfig.value.name === 'all') {
    // All选项的图标已经包含前缀
    fullIconName = tempSelectedIcon.value
  } else {
    // 其他选项需要添加前缀
    fullIconName = `${currentLibraryConfig.value.prefix}:${tempSelectedIcon.value}`
  }
  selectedIcon.value = fullIconName
  emit('update:modelValue', fullIconName)
  showPicker.value = false
}

function cancelSelection() {
  tempSelectedIcon.value = ''
  showPicker.value = false
}

// 处理滚动事件（无限滚动）
function handleScroll(event: Event) {
  const target = event.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 当滚动到底部附近时自动加载更多
  if (scrollHeight - scrollTop - clientHeight < 100 && hasMoreIcons.value && !loading.value) {
    loadMoreIcons()
  }
}

// 处理搜索变化
function handleSearch() {
  // 搜索时重置分页
  currentPage.value = 1
}

// 处理图标库切换
async function handleLibraryChange(newLibrary: string) {
  currentLibrary.value = newLibrary
  await loadAllIcons()
  // 保持搜索关键词，只清空临时选择
  tempSelectedIcon.value = ''
}

// 获取显示名称（去掉前缀）
function getDisplayName(iconName: string): string {
  if (iconName && iconName.includes(':')) {
    return iconName.split(':')[1]
  }
  return iconName
}

// 处理图标加载错误
function handleIconError(event: Event) {
  console.warn('Icon failed to load:', event)
  // 可以在这里添加错误处理逻辑，比如显示默认图标
}

// 复制图标名称
async function copyIconName(iconName: string) {
  const fullIconName = currentLibraryConfig.value.name === 'all' 
    ? iconName 
    : `${currentLibraryConfig.value.prefix}:${iconName}`
  
  await navigator.clipboard.writeText(fullIconName)
  message.success(`${t('Icon name copied to clipboard')}: ${fullIconName}`)
}

// 组件挂载时加载图标
onMounted(() => {
  loadAllIcons()
})
</script>

<style scoped>
.icon-picker {
  width: 100%;
}

.icon-trigger {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.icon-picker-content {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-count {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.loading-text {
  color: #18a058;
  margin-left: 8px;
}

.icon-grid {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
  padding: 10px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px 12px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
  background-color: #fff;
  height: 100px;
  min-height: 100px;
  position: relative; 
}

.icon-item:hover {
  border-color: #18a058;
  box-shadow: 0 2px 8px rgba(24, 160, 88, 0.1);
  transform: translateY(-2px);
}

.icon-item.active {
  border-color: #18a058;
  background-color: #e6f7ed;
  box-shadow: 0 0 0 2px rgba(24, 160, 88, 0.2);
}

.icon-wrapper {
  margin-bottom: 8px;
  color: #333;
  flex-shrink: 0; /* 防止图标区域被压缩 */
}

.icon-wrapper svg {
  width: 32px !important;
  height: 32px !important;
}

.icon-name {
  font-size: 12px;
  color: #666;
  word-break: break-all;
  line-height: 1.2;
  max-height: 2.4em; /* 最多显示2行 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 复制按钮样式 */
.copy-button {
  position: absolute;
  top: 4px;
  right: 4px;
  padding: 2px 6px;
  font-size: 11px;
  font-weight: 500;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #ddd;
  border-radius: 3px;
  cursor: pointer;
  opacity: 0;
  transition: all 0.2s ease;
  z-index: 10;
}

.copy-button:hover {
  background: #18a058;
  border-color: #18a058;
  color: white;
  opacity: 1 !important;
}

.icon-item:hover .copy-button {
  opacity: 0.8;
}

/* 加载更多和加载状态样式 */
.load-more, .loading-more {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #fafafa;
}

.load-more:hover {
  border-color: #18a058;
  background-color: #f0f9f4;
}

.load-more span, .loading-more span {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.loading-more {
  cursor: default;
  border-style: solid;
}

.spinning {
  animation: spin 1s linear infinite;
}

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

/* 响应式调整 */
@media (min-width: 768px) {
  .icon-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }

  .icon-item {
    height: 110px; /* 大屏幕下稍微高一点 */
    min-height: 110px;
  }

  .icon-name {
    font-size: 14px;
  }
}

@media (min-width: 1200px) {
  .icon-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }

  .icon-item {
    height: 120px; /* 超大屏幕下更高 */
    min-height: 120px;
  }
}
</style>