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

interface ProjectStore {
  projects: SeriesProject[]
  currentProject: SeriesProject | null
  episodes: Episode[]
  loading: 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>
  executeEpisode: (projectId: string, episodeNumber: number, title?: string) => Promise<void>
  clearCurrentProject: () => void
}

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

  fetchProjects: async () => {
    set({ loading: true, error: null })
    try {
      const projects = await projectService.listProjects()
      set({ projects, 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({ loading: true, error: null })
    try {
      const episodes = await projectService.listEpisodes(projectId)
      set({ episodes, loading: false })
    } catch (error) {
      set({ error: (error as Error).message, loading: false })
    }
  },

  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: [] })
  }
}))
