/**
 * 项目状态管理 (Zustand)
 */
import { create } from 'zustand'
import { projectService, SeriesProject, Episode } from '@/services/projectService'

interface ProjectStore {
  projects: SeriesProject[]
  currentProject: SeriesProject | null
  episodes: Episode[]
  loading: boolean
  loadingEpisodes: boolean
  error: string | null

  // Actions
  fetchProjects: () => Promise<void>
  fetchProject: (id: string) => Promise<void>
  createProject: (data: any) => Promise<SeriesProject>
  updateProject: (id: string, data: any) => Promise<void>
  deleteProject: (id: string) => Promise<void>
  fetchEpisodes: (projectId: string) => Promise<void>
  updateEpisodeInList: (episode: Episode) => void
  executeEpisode: (projectId: string, episodeNumber: number, title?: string) => Promise<void>
  clearCurrentProject: () => void
}

export const useProjectStore = create<ProjectStore>((set, get) => ({
  projects: [],
  currentProject: null,
  episodes: [],
  loading: false,
  loadingEpisodes: false,
  error: null,

  fetchProjects: async () => {
    set({ loading: true, error: null })
    try {
      const projects = await projectService.listProjects()
      // 为每个项目获取剧集数据，用于计算完成度
      const projectsWithEpisodes = await Promise.all(
        projects.map(async (project) => {
          try {
            const episodes = await projectService.listEpisodes(project.id)
            return { ...project, episodes }
          } catch {
            // 如果获取剧集失败，返回空剧集数组
            return { ...project, episodes: [] }
          }
        })
      )
      set({ projects: projectsWithEpisodes, loading: false })
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
    }
  },

  fetchProject: async (id: string) => {
    set({ loading: true, error: null })
    try {
      const project = await projectService.getProject(id)
      set({ currentProject: project, loading: false })
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
    }
  },

  createProject: async (data) => {
    set({ loading: true, error: null })
    try {
      const project = await projectService.createProject(data)
      set((state) => ({
        projects: [...state.projects, project],
        loading: false
      }))
      return project
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
      throw error
    }
  },

  updateProject: async (id, data) => {
    set({ loading: true, error: null })
    try {
      const project = await projectService.updateProject(id, data)
      set((state) => ({
        currentProject: project,
        projects: state.projects.map(p => p.id === id ? project : p),
        loading: false
      }))
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
    }
  },

  deleteProject: async (id) => {
    set({ loading: true, error: null })
    try {
      await projectService.deleteProject(id)
      set((state) => ({
        projects: state.projects.filter(p => p.id !== id),
        currentProject: state.currentProject?.id === id ? null : state.currentProject,
        loading: false
      }))
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
    }
  },

  fetchEpisodes: async (projectId: string) => {
    set({ loadingEpisodes: true, error: null })
    try {
      const episodes = await projectService.listEpisodes(projectId)
      set({ episodes, loadingEpisodes: false })
    } catch (error) {
      set({ error: (error as Error).message, loadingEpisodes: false })
    }
  },

  updateEpisodeInList: (episode: Episode) => {
    set((state) => ({
      episodes: state.episodes.map(ep => ep.id === episode.id ? episode : ep)
    }))
  },

  executeEpisode: async (projectId, episodeNumber, title) => {
    set({ loading: true, error: null })
    try {
      const result = await projectService.executeEpisode(projectId, episodeNumber, title)
      if (result.success) {
        set((state) => ({
          episodes: [...state.episodes, result.episode],
          loading: false
        }))
      } else {
        set({ error: result.message, loading: false })
      }
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
    }
  },

  clearCurrentProject: () => {
    set({ currentProject: null, episodes: [] })
  }
}))
