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

export const useBookmarkStore = defineStore('bookmark', () => {
  // 状态
  const bookmarks = ref<Bookmark[]>([])
  const loading = ref(false)
  const currentTag = 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.lastVisitTime)
      .sort((a, b) => new Date(b.lastVisitTime!).getTime() - new Date(a.lastVisitTime!).getTime())
      .slice(0, 8)
  })

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

  const filteredBookmarks = computed(() => {
    if (!currentTag.value) {
      return sortedBookmarks.value
    }
    return sortedBookmarks.value.filter(b => b.tags.includes(currentTag.value!))
  })

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

  // 搜索书签
  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.lastVisitTime = 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,
    loading,
    currentTag,
    searchKeyword,
    searchResults,
    // 计算属性
    sortedBookmarks,
    recentBookmarks,
    frequentBookmarks,
    filteredBookmarks,
    // 方法
    fetchBookmarks,
    searchBookmarks,
    clearSearch,
    createBookmark,
    updateBookmark,
    deleteBookmark,
    batchDeleteBookmarks,
    setVisibility,
    recordVisit,
    setCurrentTag,
    importBookmarks,
    exportBookmarks
  }
})

