import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { bookmarkApi } from '@/api/bookmark'
import type { Bookmark, CreateBookmarkRequest, UpdateBookmarkRequest, VisibilityType, Folder } from '@/types'

export const useBookmarkStore = defineStore('bookmark', () => {
  // 状态
  const bookmarks = ref<Bookmark[]>([])
  const folders = ref<Folder[]>([])
  const loading = ref(false)
  const currentTag = ref<string | null>(null)
  const currentFolderId = ref<string | null>(null)
  const searchKeyword = ref('')
  const searchResults = ref<Bookmark[]>([])

  // 计算属性
  const sortedBookmarks = computed(() => {
    return [...bookmarks.value].sort((a, b) => b.order - a.order)
  })

  const recentBookmarks = computed(() => {
    return [...bookmarks.value]
      .filter(b => b.lastVisitAt)
      .sort((a, b) => new Date(b.lastVisitAt!).getTime() - new Date(a.lastVisitAt!).getTime())
      .slice(0, 8)
  })

  const frequentBookmarks = computed(() => {
    return [...bookmarks.value]
      .sort((a, b) => b.visitCount - a.visitCount)
      .slice(0, 8)
  })

  const filteredBookmarks = computed(() => {
    let result = sortedBookmarks.value

    // 按文件夹过滤
    if (currentFolderId.value) {
      result = result.filter(b => b.folderId === currentFolderId.value)
    }

    // 按标签过滤
    if (currentTag.value) {
      result = result.filter(b => b.tags.some(t => t.name === currentTag.value))
    }

    return result
  })

  // 获取书签列表
  async function fetchBookmarks(tag?: string, folderId?: string) {
    loading.value = true
    try {
      const response = await bookmarkApi.getBookmarks(tag, folderId)
      if (response.success && response.data) {
        bookmarks.value = response.data
      }
    } finally {
      loading.value = false
    }
  }

  // 获取文件夹列表
  async function fetchFolders() {
    try {
      const response = await bookmarkApi.getFolders()
      if (response.success && response.data) {
        folders.value = response.data
      }
    } catch {
      // 文件夹功能可能尚未实现，静默处理
    }
  }

  // 创建文件夹
  async function createFolder(name: string, parentId?: string, icon?: string) {
    const response = await bookmarkApi.createFolder({ name, parentId, icon })
    if (response.success && response.data) {
      folders.value.push(response.data)
    }
    return response
  }

  // 删除文件夹
  async function deleteFolder(id: string) {
    const response = await bookmarkApi.deleteFolder(id)
    if (response.success) {
      folders.value = folders.value.filter(f => f.id !== id)
    }
    return response
  }

  // 设置当前文件夹
  function setCurrentFolder(folderId: string | null) {
    currentFolderId.value = folderId
  }

  // 移动书签到文件夹
  async function moveBookmarkToFolder(bookmarkId: string, folderId: string | null) {
    const response = await bookmarkApi.moveBookmarkToFolder(bookmarkId, folderId)
    if (response.success) {
      const bookmark = bookmarks.value.find(b => b.id === bookmarkId)
      if (bookmark) {
        bookmark.folderId = folderId ?? undefined
      }
    }
    return response
  }

  // 搜索书签
  async function searchBookmarks(keyword: string) {
    if (!keyword.trim()) {
      searchResults.value = []
      return
    }
    searchKeyword.value = keyword
    const response = await bookmarkApi.searchBookmarks(keyword)
    if (response.success && response.data) {
      searchResults.value = response.data
    }
  }

  // 清空搜索
  function clearSearch() {
    searchKeyword.value = ''
    searchResults.value = []
  }

  // 创建书签
  async function createBookmark(data: CreateBookmarkRequest) {
    const response = await bookmarkApi.createBookmark(data)
    if (response.success && response.data) {
      bookmarks.value.unshift(response.data)
    }
    return response
  }

  // 更新书签
  async function updateBookmark(id: string, data: UpdateBookmarkRequest) {
    const response = await bookmarkApi.updateBookmark(id, data)
    if (response.success && response.data) {
      const index = bookmarks.value.findIndex(b => b.id === id)
      if (index !== -1) {
        bookmarks.value[index] = response.data
      }
    }
    return response
  }

  // 删除书签
  async function deleteBookmark(id: string) {
    const response = await bookmarkApi.deleteBookmark(id)
    if (response.success) {
      bookmarks.value = bookmarks.value.filter(b => b.id !== id)
    }
    return response
  }

  // 批量删除
  async function batchDeleteBookmarks(ids: string[]) {
    const response = await bookmarkApi.batchDeleteBookmarks(ids)
    if (response.success) {
      bookmarks.value = bookmarks.value.filter(b => !ids.includes(b.id))
    }
    return response
  }

  // 设置可见性
  async function setVisibility(id: string, visibility: VisibilityType, allowedDevices?: string[]) {
    const response = await bookmarkApi.setVisibility(id, visibility, allowedDevices)
    if (response.success) {
      const bookmark = bookmarks.value.find(b => b.id === id)
      if (bookmark) {
        bookmark.visibility = visibility
        bookmark.allowedDevices = allowedDevices
      }
    }
    return response
  }

  // 记录访问
  async function recordVisit(id: string) {
    await bookmarkApi.recordVisit(id)
    const bookmark = bookmarks.value.find(b => b.id === id)
    if (bookmark) {
      bookmark.visitCount++
      bookmark.lastVisitAt = new Date().toISOString()
    }
  }

  // 设置当前标签
  function setCurrentTag(tag: string | null) {
    currentTag.value = tag
  }

  // 导入书签
  async function importBookmarks(data: CreateBookmarkRequest[]) {
    const response = await bookmarkApi.importBookmarks(data)
    if (response.success) {
      await fetchBookmarks()
    }
    return response
  }

  // 导出书签
  async function exportBookmarks() {
    return await bookmarkApi.exportBookmarks()
  }

  return {
    // 状态
    bookmarks,
    folders,
    loading,
    currentTag,
    currentFolderId,
    searchKeyword,
    searchResults,
    // 计算属性
    sortedBookmarks,
    recentBookmarks,
    frequentBookmarks,
    filteredBookmarks,
    // 方法
    fetchBookmarks,
    fetchFolders,
    createFolder,
    deleteFolder,
    setCurrentFolder,
    moveBookmarkToFolder,
    searchBookmarks,
    clearSearch,
    createBookmark,
    updateBookmark,
    deleteBookmark,
    batchDeleteBookmarks,
    setVisibility,
    recordVisit,
    setCurrentTag,
    importBookmarks,
    exportBookmarks
  }
})
