import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as workspaceApi from '@/api/workspace'

export const useWorkspaceStore = defineStore('workspace', () => {
  const currentPeriod = ref(null)
  const availablePeriods = ref([])
  const currentPhase = ref(null)
  const todos = ref([])
  const allowedActions = ref([])
  const teamSummary = ref(null)
  const risks = ref([])
  const deadlines = ref([])
  const loading = ref(false)
  const error = ref(null)

  const hasPeriod = computed(() => !!currentPeriod.value)

  const periodId = computed(() => {
    // URL takes precedence
    try {
      const route = useRoute()
      if (route.query.periodId) return Number(route.query.periodId)
    } catch {}
    return currentPeriod.value?.id || null
  })

  async function refreshOverview(explicitPeriodId) {
    loading.value = true
    error.value = null
    try {
      const res = await workspaceApi.getOverview(explicitPeriodId)
      const data = res.data
      currentPeriod.value = data.recommendedPeriod
      availablePeriods.value = data.availablePeriods || []
      currentPhase.value = data.currentPhase
      todos.value = data.myTodos || []
      allowedActions.value = data.allowedActions || []
      teamSummary.value = data.teamSummary
      risks.value = data.risks || []
      deadlines.value = data.upcomingDeadlines || []
    } catch (e) {
      error.value = e.message || '加载工作台失败'
    } finally {
      loading.value = false
    }
  }

  async function selectPeriod(id) {
    try {
      const router = useRouter()
      const route = useRoute()
      router.replace({ query: { ...route.query, periodId: id } })
    } catch {}
    await refreshOverview(id)
  }

  return {
    currentPeriod, availablePeriods, currentPhase,
    todos, allowedActions, teamSummary, risks, deadlines,
    loading, error, hasPeriod, periodId,
    refreshOverview, selectPeriod
  }
})
