import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { tagApi } from '@/api/tag'
import type { Tag } from '@/types'

export const useTagStore = defineStore('tag', () => {
  // 状态
  const tags = ref<Tag[]>([])
  const loading = ref(false)

  // 计算属性 - 按 order 排序，如果 order 相同则按使用次数排序
  const sortedTags = computed(() => {
    return [...tags.value].sort((a, b) => {
      if (a.order !== b.order) {
        return a.order - b.order
      }
      return b.count - a.count
    })
  })

  // 按使用次数排序
  const tagsByCount = computed(() => {
    return [...tags.value].sort((a, b) => b.count - a.count)
  })

  const tagNames = computed(() => {
    return tags.value.map(t => t.name)
  })

  // 根据名称查找标签
  function getTagByName(name: string): Tag | undefined {
    return tags.value.find(t => t.name === name)
  }

  // 根据 ID 查找标签
  function getTagById(id: string): Tag | undefined {
    return tags.value.find(t => t.id === id)
  }

  // 获取标签列表
  async function fetchTags() {
    loading.value = true
    try {
      const response = await tagApi.getTags()
      if (response.success && response.data) {
        tags.value = response.data
      }
    } finally {
      loading.value = false
    }
  }

  // 创建标签
  async function createTag(name: string, color?: string, icon?: string) {
    const response = await tagApi.createTag({ name, color, icon })
    if (response.success && response.data) {
      tags.value.push(response.data)
    }
    return response
  }

  // 更新标签
  async function updateTag(id: string, data: { name?: string; color?: string; icon?: string; order?: number }) {
    const response = await tagApi.updateTag(id, data)
    if (response.success && response.data) {
      const index = tags.value.findIndex(t => t.id === id)
      if (index !== -1) {
        tags.value[index] = response.data
      }
    }
    return response
  }

  // 删除标签（通过 ID）
  async function deleteTag(id: string) {
    const response = await tagApi.deleteTag(id)
    if (response.success) {
      tags.value = tags.value.filter(t => t.id !== id)
    }
    return response
  }

  // 合并标签（使用标签 ID）
  async function mergeTags(sourceTagIds: string[], targetTagId: string) {
    const response = await tagApi.mergeTags(sourceTagIds, targetTagId)
    if (response.success) {
      await fetchTags()
    }
    return response
  }

  return {
    // 状态
    tags,
    loading,
    // 计算属性
    sortedTags,
    tagsByCount,
    tagNames,
    // 方法
    getTagByName,
    getTagById,
    fetchTags,
    createTag,
    updateTag,
    deleteTag,
    mergeTags
  }
})
