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

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

  const filteredProjects = computed(() => {
    if (filterType.value === 'all') return projects.value
    return projects.value.filter(p => p.cooperationType === 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 === 'in_progress').length)
  const completedCount = computed(() => projects.value.filter(p => p.status === 'completed').length)
  const hasMore = computed(() => projects.value.length < total.value)

  async function fetchProjects(reset = false) {
    if (reset) {
      pageNum.value = 1
      projects.value = []
    }

    loading.value = true
    try {
      const res = await getProjectList(pageNum.value, pageSize.value)
      const rows = res.rows || []
      projects.value = reset ? rows : [...projects.value, ...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: CooperationType | 'all') {
    filterType.value = type
  }

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

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

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