import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { episodeService, type Episode, type EpisodeCreate, type EpisodeUpdate } from '@/services/episode'

export const useEpisodesStore = defineStore('episodes', () => {
  // State
  const episodes = ref<Episode[]>([])
  const currentEpisode = ref<Episode | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const getEpisodeById = computed(() => {
    return (id: number) => episodes.value.find(episode => episode.id === id)
  })

  const getEpisodesByProject = computed(() => {
    return (projectId: number) => episodes.value.filter(episode => episode.project_id === projectId)
  })

  const episodesByStatus = computed(() => {
    return (status: string) => episodes.value.filter(episode => episode.status === status)
  })

  // Actions
  const fetchEpisodes = async (projectId?: number) => {
    try {
      isLoading.value = true
      error.value = null
      
      if (projectId) {
        episodes.value = await episodeService.getProjectEpisodes(projectId)
      } else {
        episodes.value = await episodeService.getEpisodes()
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to fetch episodes'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const fetchEpisode = async (episodeId: number) => {
    try {
      isLoading.value = true
      error.value = null
      
      const episode = await episodeService.getEpisode(episodeId)
      
      // Update the episode in the list if it exists
      const index = episodes.value.findIndex(e => e.id === episodeId)
      if (index !== -1) {
        episodes.value[index] = episode
      } else {
        episodes.value.push(episode)
      }
      
      currentEpisode.value = episode
      return episode
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to fetch episode'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const createEpisode = async (projectId: number, episodeData: EpisodeCreate) => {
    try {
      isLoading.value = true
      error.value = null
      
      const newEpisode = await episodeService.createEpisode(projectId, episodeData)
      episodes.value.push(newEpisode)
      
      return newEpisode
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to create episode'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const updateEpisode = async (episodeId: number, episodeData: EpisodeUpdate) => {
    try {
      isLoading.value = true
      error.value = null
      
      const updatedEpisode = await episodeService.updateEpisode(episodeId, episodeData)
      
      // Update the episode in the list
      const index = episodes.value.findIndex(e => e.id === episodeId)
      if (index !== -1) {
        episodes.value[index] = updatedEpisode
      }
      
      // Update current episode if it's the same
      if (currentEpisode.value?.id === episodeId) {
        currentEpisode.value = updatedEpisode
      }
      
      return updatedEpisode
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to update episode'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const deleteEpisode = async (episodeId: number) => {
    try {
      isLoading.value = true
      error.value = null
      
      await episodeService.deleteEpisode(episodeId)
      
      // Remove the episode from the list
      episodes.value = episodes.value.filter(e => e.id !== episodeId)
      
      // Clear current episode if it's the deleted one
      if (currentEpisode.value?.id === episodeId) {
        currentEpisode.value = null
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to delete episode'
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const setCurrentEpisode = (episode: Episode | null) => {
    currentEpisode.value = episode
  }

  const clearError = () => {
    error.value = null
  }

  const clearEpisodes = () => {
    episodes.value = []
    currentEpisode.value = null
    error.value = null
  }

  return {
    // State
    episodes,
    currentEpisode,
    isLoading,
    error,
    
    // Getters
    getEpisodeById,
    getEpisodesByProject,
    episodesByStatus,
    
    // Actions
    fetchEpisodes,
    fetchEpisode,
    createEpisode,
    updateEpisode,
    deleteEpisode,
    setCurrentEpisode,
    clearError,
    clearEpisodes
  }
})

export type { Episode, EpisodeCreate, EpisodeUpdate }