import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'

import { linkService } from '@/services/linkService'
import { tagService } from '@/services/tagService'

const RECENT_LIMIT = 15

const defaultLinkFields = {
  description: '',
  icon: '',
  tags: [],
  projectIds: [],
  visitCount: 0,
  lastVisitTime: null,
  order: 0,
}

function toDate(value) {
  if (!value) return null
  if (value instanceof Date) return value
  const parsed = new Date(value)
  return Number.isNaN(parsed.getTime()) ? null : parsed
}

function normalizeLink(link) {
  return {
    ...defaultLinkFields,
    ...link,
    tags: Array.isArray(link?.tags) ? [...link.tags] : [],
    projectIds: Array.isArray(link?.projectIds) ? [...link.projectIds] : [],
    order: link.order ?? (link.createdAt ? new Date(link.createdAt).getTime() : Date.now()),
    lastVisitTime: toDate(link?.lastVisitTime),
    createdAt: toDate(link?.createdAt) ?? new Date(),
    updatedAt: toDate(link?.updatedAt) ?? new Date(),
  }
}

function sortByCreatedDesc(collection) {
  return [...collection].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
}

export const useLinksStore = defineStore('links', () => {
  const links = ref([])
  const isLoading = ref(false)
  const isReady = ref(false)

  async function ensureLoaded() {
    if (isReady.value || isLoading.value) return
    isLoading.value = true
    try {
      const records = await linkService.getAllLinks()
      links.value = records.map(normalizeLink)
      // 初始化标签缓存
      tagService.initializeFromLinks(links.value)
      isReady.value = true
    } finally {
      isLoading.value = false
    }
  }

  function upsertInState(link) {
    const normalized = normalizeLink(link)
    const index = links.value.findIndex((item) => item.id === normalized.id)
    if (index === -1) {
      links.value = sortByCreatedDesc([normalized, ...links.value])
      return
    }
    const updated = [...links.value]
    updated.splice(index, 1, normalized)
    links.value = sortByCreatedDesc(updated)
  }

  async function addLink(payload) {
    await ensureLoaded()
    const timestamp = new Date()
    
    // 优先使用用户输入的 order，如果没有则使用时间戳作为排序值
    const record = normalizeLink({
      ...payload,
      id: payload.id ?? uuidv4(),
      order: payload.order !== undefined ? payload.order : timestamp.getTime(),
      createdAt: payload.createdAt ?? timestamp,
      updatedAt: payload.updatedAt ?? timestamp,
    })
    await linkService.addLink(record)
    upsertInState(record)
    // 更新标签缓存
    tagService.updateFromLink(record, 'add')
    return record
  }

  async function updateLink(id, updates) {
    await ensureLoaded()
    const existing = links.value.find((item) => item.id === id)
    if (!existing) throw new Error(`未找到 ID 为 "${id}" 的书签`)

    const updatedRecord = normalizeLink({
      ...existing,
      ...updates,
      id,
      updatedAt: new Date(),
    })

    await linkService.updateLink(id, updatedRecord)
    upsertInState(updatedRecord)
    // 更新标签缓存（需要传入旧书签以处理标签变更）
    tagService.updateFromLink(updatedRecord, 'update', existing)
    return updatedRecord
  }

  async function removeLink(id) {
    await ensureLoaded()
    const existing = links.value.find((item) => item.id === id)
    await linkService.deleteLink(id)
    links.value = links.value.filter((item) => item.id !== id)
    // 更新标签缓存
    if (existing) {
      tagService.updateFromLink(existing, 'remove')
    }
  }

  async function recordVisit(id) {
    await ensureLoaded()
    const existing = links.value.find((item) => item.id === id)
    if (!existing) return null

    const updated = await linkService.recordVisit(id)
    if (updated) {
      const normalized = normalizeLink(updated)
      upsertInState(normalized)
      return normalized
    }
    return null
  }

  async function importLinks(externalLinks, { replace = false } = {}) {
    await ensureLoaded()
    const normalized = externalLinks
      .map((link) => {
        const candidate = normalizeLink({
          ...link,
          id: link.id ?? uuidv4(),
        })
        return { ...candidate, lastVisitTime: candidate.lastVisitTime ?? null }
      })
      .filter((link) => Boolean(link.title) && Boolean(link.url))

    await linkService.importLinks(normalized, { replace })

    const records = await linkService.getAllLinksByCreated()
    links.value = records.map(normalizeLink)
    // 重新初始化标签缓存
    tagService.initializeFromLinks(links.value)
    isReady.value = true
    return links.value.length
  }

  async function exportLinks() {
    await ensureLoaded()
    return await linkService.exportLinks()
  }

  async function clearAll() {
    await linkService.clearAll()
    links.value = []
    // 清空标签缓存
    tagService.clear()
    isReady.value = true
  }

  const totalCount = computed(() => links.value.length)

  const recentLinks = computed(() => {
    return [...links.value]
      .map((item) => {
        const referenceTime = item.lastVisitTime ?? item.updatedAt ?? item.createdAt ?? null
        return {
          item,
          referenceTime,
        }
      })
      .filter(({ referenceTime }) => referenceTime instanceof Date && !Number.isNaN(referenceTime.getTime()))
      .sort((a, b) => b.referenceTime.getTime() - a.referenceTime.getTime())
      .slice(0, RECENT_LIMIT)
      .map(({ item }) => item)
  })

  const favorites = computed(() => {
    return [...links.value]
      .filter((item) => (item.visitCount ?? 0) > 0)
      .sort((a, b) => {
        if (b.visitCount === a.visitCount) {
          return b.updatedAt.getTime() - a.updatedAt.getTime()
        }
        return b.visitCount - a.visitCount
      })
      .slice(0, 20)
  })

  const allTags = computed(() => {
    return tagService.getAllTags()
  })

  // 按标签分组的书签映射（需要传入标签顺序）
  function getLinksByTagWithOrder(tagOrder = null) {
    return tagService.getLinksByTag(links.value, tagOrder)
  }
  
  // 按标签分组的书签映射（使用默认顺序）
  const linksByTag = computed(() => {
    return tagService.getLinksByTag(links.value, null)
  })

  async function importBrowserBookmarks(bookmarkItems, options = {}) {
    await ensureLoaded()

    const result = {
      success: 0,
      skipped: 0,
      failed: 0,
    }

    // 获取现有书签的 URL 集合，用于检测重复
    const existingUrls = new Set(links.value.map((link) => link.url.toLowerCase()))

    // 转换并过滤书签
    const bookmarksToImport = []
    for (const item of bookmarkItems) {
      // 验证必需字段
      if (!item.title || !item.url) {
        result.failed++
        continue
      }

      // 检测重复
      if (existingUrls.has(item.url.toLowerCase())) {
        result.skipped++
        continue
      }

      // 转换为应用格式
      const bookmark = normalizeLink({
        ...item,
        id: item.id ?? uuidv4(),
        createdAt: item.createdAt ?? new Date(),
        updatedAt: item.updatedAt ?? new Date(),
      })

      bookmarksToImport.push(bookmark)
      existingUrls.add(item.url.toLowerCase()) // 避免同一批次内的重复
    }

    // 批量导入
    if (bookmarksToImport.length > 0) {
      try {
        await linkService.bulkAddLinks(bookmarksToImport)

        // 更新状态
        const records = await linkService.getAllLinksByCreated()
        links.value = records.map(normalizeLink)
        // 重新初始化标签缓存
        tagService.initializeFromLinks(links.value)
        isReady.value = true

        result.success = bookmarksToImport.length
      } catch (error) {
        console.error('导入书签失败:', error)
        result.failed += bookmarksToImport.length
      }
    }

    return result
  }

  // 按order排序的书签列表
  const sortedLinks = computed(() => {
    return [...links.value].sort((a, b) => {
      const orderA = a.order ?? 0
      const orderB = b.order ?? 0
      return orderA - orderB
    })
  })

  // 拖拽排序功能
  async function reorderLinks(draggedItem, targetItem, direction) {
    console.log('🔄 Store reorderLinks 开始:', {
      draggedItem: draggedItem ? {
        id: draggedItem.id,
        title: draggedItem.title,
        order: draggedItem.order
      } : null,
      targetItem: targetItem ? {
        id: targetItem.id,
        title: targetItem.title,
        order: targetItem.order
      } : null,
      direction
    })
    
    await ensureLoaded()
    
    if (!draggedItem || !targetItem) {
      console.error('❌ Store reorderLinks: 缺少必要参数', {
        hasDraggedItem: !!draggedItem,
        hasTargetItem: !!targetItem
      })
      throw new Error('缺少必要的排序参数')
    }

    console.log('📋 当前书签总数:', links.value.length)
    console.log('📝 当前书签列表:', links.value.map(link => ({
      id: link.id,
      title: link.title,
      order: link.order
    })))

    // 创建新的排序数组
    const items = [...links.value]
    const draggedIndex = items.findIndex(item => item.id === draggedItem.id)
    const targetIndex = items.findIndex(item => item.id === targetItem.id)
    
    console.log('🔍 索引查找结果:', {
      draggedIndex,
      targetIndex,
      draggedItemId: draggedItem.id,
      targetItemId: targetItem.id
    })
    
    if (draggedIndex === -1) {
      console.error('❌ 未找到被拖拽项目:', draggedItem.id)
      throw new Error(`未找到被拖拽的项目: ${draggedItem.id}`)
    }
    
    if (targetIndex === -1) {
      console.error('❌ 未找到目标项目:', targetItem.id)
      throw new Error(`未找到目标项目: ${targetItem.id}`)
    }

    // 移除被拖拽的项目
    const removed = items.splice(draggedIndex, 1)[0]
    console.log('🗑️  移除项目:', {
      removed: removed ? {
        id: removed.id,
        title: removed.title
      } : null,
      '移除后数组长度': items.length
    })
    
    // 计算新的索引
    let newIndex = targetIndex
    if (direction === 'after' && draggedIndex < targetIndex) {
      newIndex = targetIndex - 1
    } else if (direction === 'before' && draggedIndex > targetIndex) {
      newIndex = targetIndex + 1
    } else if (direction === 'after' && draggedIndex > targetIndex) {
      newIndex = targetIndex + 1
    }
    
    console.log('📍 计算新位置:', {
      direction,
      originalDraggedIndex: draggedIndex,
      originalTargetIndex: targetIndex,
      newIndex
    })
    
    // 确保索引在有效范围内
    newIndex = Math.max(0, Math.min(newIndex, items.length))
    
    // 插入到新位置
    items.splice(newIndex, 0, removed)
    console.log('➕ 插入新位置后数组长度:', items.length)
    console.log('📋 新的顺序:', items.map((item, index) => `${index + 1}. ${item.title} (order: ${item.order})`))

    // 重新计算排序值
    const now = Date.now()
    console.log('⏰ 当前时间戳:', now)
    
    const updates = items.map((item, index) => ({
      id: item.id,
      order: now + index * 1000, // 使用时间戳+索引确保唯一性和顺序
      updatedAt: new Date(),
    }))
    
    console.log('🆕 新的排序值:', updates.map(update => ({
      id: update.id,
      newOrder: update.order
    })))

    try {
      console.log('💾 开始数据库事务...')
      // 批量更新数据库
      await linkService.reorderLinks(updates)

      console.log('🔄 更新内存状态...')
      // 更新状态
      const updatedLinks = items.map(item => {
        const update = updates.find(u => u.id === item.id)
        return {
          ...item,
          order: update.order,
          updatedAt: update.updatedAt,
        }
      })
      
      links.value = updatedLinks
      isReady.value = true
      
      console.log('🎉 排序更新完成!')
      console.log('📊 最终排序结果:', updatedLinks.map((link, index) => ({
        position: index + 1,
        id: link.id,
        title: link.title,
        order: link.order
      })))
      
    } catch (error) {
      console.error('❌ 排序更新失败:', error)
      console.error('❌ 错误堆栈:', error.stack)
      throw new Error(`排序更新失败: ${error.message}`)
    }
  }

  // 简化的重新排序方法：直接根据数组索引分配排序值
  async function reorderLinksFromArray(newArray) {
    console.log('🔄 Store reorderLinksFromArray 开始:', {
      arrayLength: newArray.length,
      array: newArray.map((item, index) => ({
        index,
        id: item.id,
        title: item.title
      }))
    })
    
    await ensureLoaded()
    
    if (!newArray || newArray.length === 0) {
      console.warn('⚠️  排序数组为空')
      return
    }
    
    try {
      // 重新分配排序值
      const now = Date.now()
      const updates = newArray.map((item, index) => ({
        id: item.id,
        order: now + index * 1000, // 使用时间戳+索引确保唯一性和顺序
        updatedAt: new Date(),
      }))
      
      console.log('🆕 新的排序值:', updates.map(update => ({
        id: update.id,
        newOrder: update.order
      })))
      
      console.log('💾 开始数据库事务...')
      
      // 批量更新数据库
      await linkService.reorderLinks(updates)
      
      console.log('🔄 更新内存状态...')
      
      // 更新状态
      const updatedLinks = newArray.map((item, index) => {
        const update = updates.find(u => u.id === item.id)
        return {
          ...item,
          order: update.order,
          updatedAt: update.updatedAt,
        }
      })
      
      links.value = updatedLinks
      isReady.value = true
      
      console.log('🎉 排序更新完成!')
      console.log('📊 最终排序结果:', updatedLinks.map((link, index) => ({
        position: index + 1,
        id: link.id,
        title: link.title,
        order: link.order
      })))
      
    } catch (error) {
      console.error('❌ 排序更新失败:', error)
      console.error('❌ 错误堆栈:', error.stack)
      throw new Error(`排序更新失败: ${error.message}`)
    }
  }

  return {
    links: sortedLinks, // 使用排序后的列表
    totalCount,
    recentLinks,
    favorites,
    allTags,
    linksByTag, // 按标签分组的书签映射
    getLinksByTagWithOrder, // 按标签分组的书签映射（支持自定义顺序）
    isLoading,
    isReady,
    ensureLoaded,
    addLink,
    updateLink,
    removeLink,
    recordVisit,
    importLinks,
    exportLinks,
    clearAll,
    importBrowserBookmarks,
    reorderLinks,
    reorderLinksFromArray,
  }
})

