/**
 * Review Card Store
 *
 * 审核卡片状态管理
 */
import { create } from 'zustand'
import { reviewCardService, ReviewCard, ReviewCardStats, ReviewCardStatus, ReviewCardType } from '@/services/reviewCardService'

interface ReviewCardState {
  // 数据
  cards: ReviewCard[]
  currentCard: ReviewCard | null
  stats: ReviewCardStats | null

  // 筛选状态
  statusFilter: ReviewCardStatus | 'all'
  typeFilter: ReviewCardType | 'all'
  searchQuery: string

  // UI 状态
  loading: boolean
  error: string | null

  // 操作
  setProjectId: (projectId: string) => void
  setStatusFilter: (status: ReviewCardStatus | 'all') => void
  setTypeFilter: (type: ReviewCardType | 'all') => void
  setSearchQuery: (query: string) => void

  // 数据获取
  fetchCards: (projectId: string, status?: ReviewCardStatus) => Promise<void>
  fetchStats: (projectId: string) => Promise<void>
  fetchCard: (cardId: string) => Promise<void>

  // 操作
  approveCard: (cardId: string, userComment?: string) => Promise<void>
  rejectCard: (cardId: string, userComment?: string, modifiedContent?: string) => Promise<void>
  modifyCard: (cardId: string, userComment?: string, modifiedContent?: string) => Promise<void>
  deleteCard: (cardId: string) => Promise<void>

  // 清理
  clearCards: () => void
  clearCurrentCard: () => void
}

export const useReviewCardStore = create<ReviewCardState>((set, get) => ({
  // 初始状态
  cards: [],
  currentCard: null,
  stats: null,
  statusFilter: 'all',
  typeFilter: 'all',
  searchQuery: '',
  loading: false,
  error: null,

  // 设置项目ID（预留）
  setProjectId: (projectId: string) => {
    // 可以在这里设置当前项目ID
  },

  // 设置筛选状态
  setStatusFilter: (status) => set({ statusFilter: status }),
  setTypeFilter: (type) => set({ typeFilter: type }),
  setSearchQuery: (query) => set({ searchQuery: query }),

  // 获取卡片列表
  fetchCards: async (projectId, status) => {
    set({ loading: true, error: null })
    try {
      const cards = await reviewCardService.listCards(projectId, status)
      set({ cards, loading: false })
    } catch (error: any) {
      set({ error: error?.message || '获取卡片列表失败', loading: false })
    }
  },

  // 获取统计信息
  fetchStats: async (projectId) => {
    try {
      const stats = await reviewCardService.getStats(projectId)
      set({ stats })
    } catch (error: any) {
      console.error('获取统计信息失败:', error)
    }
  },

  // 获取卡片详情
  fetchCard: async (cardId) => {
    set({ loading: true, error: null })
    try {
      const card = await reviewCardService.getCard(cardId)
      set({ currentCard: card, loading: false })
    } catch (error: any) {
      set({ error: error?.message || '获取卡片详情失败', loading: false })
    }
  },

  // 通过审核
  approveCard: async (cardId, userComment) => {
    set({ loading: true, error: null })
    try {
      const result = await reviewCardService.approveCard(cardId, userComment)
      // 更新列表中的卡片
      set((state) => ({
        cards: state.cards.map(c => c.id === cardId ? result.card : c),
        currentCard: state.currentCard?.id === cardId ? result.card : state.currentCard,
        loading: false
      }))
      // 重新获取统计信息
      const projectId = get().currentCard?.project_id
      if (projectId) {
        get().fetchStats(projectId)
      }
    } catch (error: any) {
      set({ error: error?.message || '操作失败', loading: false })
      throw error
    }
  },

  // 驳回审核
  rejectCard: async (cardId, userComment, modifiedContent) => {
    set({ loading: true, error: null })
    try {
      const result = await reviewCardService.rejectCard(cardId, userComment, modifiedContent)
      set((state) => ({
        cards: state.cards.map(c => c.id === cardId ? result.card : c),
        currentCard: state.currentCard?.id === cardId ? result.card : state.currentCard,
        loading: false
      }))
      const projectId = get().currentCard?.project_id
      if (projectId) {
        get().fetchStats(projectId)
      }
    } catch (error: any) {
      set({ error: error?.message || '操作失败', loading: false })
      throw error
    }
  },

  // 修改审核
  modifyCard: async (cardId, userComment, modifiedContent) => {
    set({ loading: true, error: null })
    try {
      const result = await reviewCardService.modifyCard(cardId, userComment, modifiedContent)
      set((state) => ({
        cards: state.cards.map(c => c.id === cardId ? result.card : c),
        currentCard: state.currentCard?.id === cardId ? result.card : state.currentCard,
        loading: false
      }))
      const projectId = get().currentCard?.project_id
      if (projectId) {
        get().fetchStats(projectId)
      }
    } catch (error: any) {
      set({ error: error?.message || '操作失败', loading: false })
      throw error
    }
  },

  // 删除卡片
  deleteCard: async (cardId) => {
    set({ loading: true, error: null })
    try {
      await reviewCardService.deleteCard(cardId)
      set((state) => ({
        cards: state.cards.filter(c => c.id !== cardId),
        currentCard: state.currentCard?.id === cardId ? null : state.currentCard,
        loading: false
      }))
      const projectId = get().cards.find(c => c.id !== cardId)?.project_id
      if (projectId) {
        get().fetchStats(projectId)
      }
    } catch (error: any) {
      set({ error: error?.message || '删除失败', loading: false })
      throw error
    }
  },

  // 清理数据
  clearCards: () => set({ cards: [], stats: null, error: null }),
  clearCurrentCard: () => set({ currentCard: null, error: null })
}))
