import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { Film, Palette, Zap, Folder } from 'lucide-vue-next'
import { projectService, type Project as ProjectType, type ProjectCreate, type ProjectUpdate } from '@/services/project'

export interface Project extends ProjectType {
  icon?: any
}

export const useProjectsStore = defineStore('projects', () => {
  // State
  const projects = ref<Project[]>([])
  const activeProject = ref<Project | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const allProjectsView: Project = {
    id: 0,
    name: 'All Projects',
    status: 'planning',
    icon: Folder,
    description: 'View all projects',
    created_at: '',
    updated_at: ''
  }

  const availableProjects = computed(() => [...projects.value, allProjectsView])
  
  const currentProject = computed(() => activeProject.value || allProjectsView)

  const projectsByStatus = computed(() => {
    const grouped: Record<string, Project[]> = {}
    projects.value.forEach(project => {
      if (!grouped[project.status]) {
        grouped[project.status] = []
      }
      grouped[project.status].push(project)
    })
    return grouped
  })

  const projectsInProgress = computed(() => 
    projects.value.filter(p => p.status === 'in_progress')
  )

  const projectsPlanning = computed(() => 
    projects.value.filter(p => p.status === 'planning')
  )

  const projectsCompleted = computed(() => 
    projects.value.filter(p => p.status === 'completed')
  )

  const projectsOnHold = computed(() => 
    projects.value.filter(p => p.status === 'on_hold')
  )

  // Helper function to assign icons based on project type and name
  const assignProjectIcon = (project: ProjectType): Project => {
    let icon = Film // default icon
    
    // Assign icon based on project type first
    switch (project.project_type) {
      case 'tv':
        icon = Palette
        break
      case 'cinema':
        icon = Film
        break
      case 'game':
        icon = Zap
        break
      default:
        // Fallback to name-based detection
        const name = project.name.toLowerCase()
        if (name.includes('series') || name.includes('episode')) {
          icon = Palette
        } else if (name.includes('commercial') || name.includes('ad')) {
          icon = Zap
        } else if (name.includes('film') || name.includes('movie')) {
          icon = Film
        }
    }
    
    return { ...project, icon }
  }

  // Actions
  const fetchProjects = async () => {
    try {
      isLoading.value = true
      error.value = null
      const fetchedProjects = await projectService.getUserProjects()
      projects.value = fetchedProjects.map(assignProjectIcon)
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to fetch projects'
      console.error('Failed to fetch projects:', err)
    } finally {
      isLoading.value = false
    }
  }

  const createProject = async (projectData: ProjectCreate) => {
    try {
      isLoading.value = true
      error.value = null
      const newProject = await projectService.createProject(projectData)
      const projectWithIcon = assignProjectIcon(newProject)
      projects.value.push(projectWithIcon)
      return projectWithIcon
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to create project'
      console.error('Failed to create project:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const updateProject = async (id: number, updates: ProjectUpdate) => {
    try {
      isLoading.value = true
      error.value = null
      const updatedProject = await projectService.updateProject(id, updates)
      const projectWithIcon = assignProjectIcon(updatedProject)
      
      const index = projects.value.findIndex(p => p.id === id)
      if (index !== -1) {
        projects.value[index] = projectWithIcon
        
        // Update active project if it's the one being updated
        if (activeProject.value?.id === id) {
          activeProject.value = projectWithIcon
        }
      }
      
      return projectWithIcon
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to update project'
      console.error('Failed to update project:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const deleteProject = async (id: number) => {
    try {
      isLoading.value = true
      error.value = null
      await projectService.deleteProject(id)
      
      const index = projects.value.findIndex(p => p.id === id)
      if (index !== -1) {
        projects.value.splice(index, 1)
        
        // If the removed project was active, switch to all projects view
        if (activeProject.value?.id === id) {
          activeProject.value = allProjectsView
        }
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to delete project'
      console.error('Failed to delete project:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const getProject = async (id: number, includeMembers: boolean = false) => {
    try {
      isLoading.value = true
      error.value = null
      const project = await projectService.getProject(id, includeMembers)
      return assignProjectIcon(project)
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to fetch project'
      console.error('Failed to fetch project:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  const setActiveProject = (project: Project) => {
    activeProject.value = project
  }

  const getProjectById = (id: number): Project | undefined => {
    if (id === 0) return allProjectsView
    return projects.value.find(p => p.id === id)
  }

  const updateProjectInStore = (updatedProject: ProjectType) => {
    const projectWithIcon = assignProjectIcon(updatedProject)
    const index = projects.value.findIndex(p => p.id === updatedProject.id)
    if (index !== -1) {
      projects.value[index] = projectWithIcon
      
      // Update active project if it's the one being updated
      if (activeProject.value?.id === updatedProject.id) {
        activeProject.value = projectWithIcon
      }
    }
  }

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

  // Initialize with all projects view
  if (!activeProject.value) {
    activeProject.value = allProjectsView
  }

  return {
    // State
    projects,
    activeProject,
    isLoading,
    error,
    
    // Getters
    availableProjects,
    currentProject,
    projectsByStatus,
    projectsInProgress,
    projectsPlanning,
    projectsCompleted,
    projectsOnHold,
    allProjectsView,
    
    // Actions
    fetchProjects,
    createProject,
    updateProject,
    deleteProject,
    getProject,
    setActiveProject,
    getProjectById,
    updateProjectInStore,
    clearError
  }
})