import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { IExpertTeamState, ITeamPlanPhase } from '@/api/types'

export const useTeamStore = defineStore('team', () => {
  const teamState = ref<IExpertTeamState | null>(null)
  const selectedExpertId = ref<string | null>(null)

  const activeExperts = computed(() =>
    teamState.value?.experts.filter(e => e.status === 'active') || []
  )

  const leadExpert = computed(() =>
    teamState.value?.experts.find(e => e.is_lead) || null
  )

  const isTeamMode = computed(() =>
    teamState.value !== null && teamState.value.status !== 'dissolved'
  )

  const currentPhase = computed(() => {
    if (!teamState.value) return null
    return teamState.value.plan_phases.find(p => p.status === 'in_progress') || null
  })

  const completedPhases = computed(() =>
    teamState.value?.plan_phases.filter(p => p.status === 'completed') || []
  )

  function setTeamState(state: IExpertTeamState) {
    teamState.value = state
  }

  function updatePhases(phases: ITeamPlanPhase[]) {
    if (teamState.value) {
      // Reassign the whole object to trigger Vue reactivity
      teamState.value = { ...teamState.value, plan_phases: phases }
    }
  }

  function updatePhaseStatus(
    phaseId: string,
    status: ITeamPlanPhase['status'],
    result?: string,
  ) {
    if (!teamState.value?.plan_phases) return
    const phases = teamState.value.plan_phases.map((p) => {
      if (p.id !== phaseId) return p
      return result !== undefined
        ? { ...p, status, result }
        : { ...p, status }
    })
    teamState.value = { ...teamState.value, plan_phases: phases }
  }

  function selectExpert(expertId: string | null) {
    selectedExpertId.value = expertId
  }

  function clearTeam() {
    teamState.value = null
    selectedExpertId.value = null
  }

  return {
    teamState, selectedExpertId, activeExperts, leadExpert,
    isTeamMode, currentPhase, completedPhases,
    setTeamState, updatePhases, updatePhaseStatus, selectExpert, clearTeam
  }
})
