import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Project } from '../types'
import { getProjectList, deleteProject as apiDeleteProject } from '../api/project'

export const useProjectStore = defineStore('project', () => {
  // State
  const projects = ref<Project[]>([])
  const currentProject = ref<Project | null>(null)
  const filterType = ref<string>('all')
  const loading = ref(false)
  const loadingMore = ref(false)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // Getters
  const filteredProjects = computed(() => {
    if (filterType.value === 'all') return projects.value
    return projects.value.filter(p => p.type === filterType.value)
  })

  const totalCount = computed(() => total.value)
  const pendingCount = computed(() => projects.value.filter(p => p.status === 'pending').length)
  const processingCount = computed(() => projects.value.filter(p => p.status === 'processing').length)
  const completedCount = computed(() => projects.value.filter(p => p.status === 'completed').length)
  const hasMore = computed(() => projects.value.length < total.value)

  // Actions
  async function fetchProjects(reset = false) {
    if (reset) {
      pageNum.value = 1
      projects.value = []
    }
    
    loading.value = true
    try {
      const res = await getProjectList(pageNum.value, pageSize.value)
      if (reset) {
        projects.value = res.rows || []
      } else {
        projects.value = [...projects.value, ...(res.rows || [])]
      }
      total.value = res.total || 0
    } finally {
      loading.value = false
    }
  }

  async function loadMore() {
    if (loadingMore.value || !hasMore.value) return
    
    loadingMore.value = true
    pageNum.value++
    try {
      const res = await getProjectList(pageNum.value, pageSize.value)
      projects.value = [...projects.value, ...(res.rows || [])]
    } catch (error) {
      pageNum.value--
    } finally {
      loadingMore.value = false
    }
  }

  function setFilter(type: string) {
    filterType.value = type
  }

  function setCurrentProject(projectId: string) {
    currentProject.value = projects.value.find(p => p.id === projectId) || null
  }

  function addProject(project: Project) {
    projects.value.unshift(project)
    total.value++
  }

  async function deleteProject(projectId: string) {
    await apiDeleteProject(Number(projectId))
    projects.value = projects.value.filter(p => p.id !== projectId)
    total.value--
  }

  return {
    projects,
    currentProject,
    filterType,
    loading,
    loadingMore,
    total,
    hasMore,
    filteredProjects,
    totalCount,
    pendingCount,
    processingCount,
    completedCount,
    fetchProjects,
    loadMore,
    setFilter,
    setCurrentProject,
    addProject,
    deleteProject,
  }
})
