package com.diegocayo.organizame.presentation.features.main.subjects.list

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.domain.model.Subject
import com.diegocayo.organizame.domain.repository.SubjectRepository
import com.diegocayo.organizame.domain.usecase.GetAllSubjectsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed class SubjectsListEvent {
    data class DeleteSubject(val subject: Subject) : SubjectsListEvent()
}

@HiltViewModel
class SubjectsListViewModel @Inject constructor(
    private val getAllSubjectsUseCase: GetAllSubjectsUseCase,
    private val subjectRepository: SubjectRepository
) : ViewModel() {

    private val _state = MutableStateFlow(SubjectsListState())
    val state: StateFlow<SubjectsListState> = _state.asStateFlow()

    init {
        loadSubjects()
    }

    fun onEvent(event: SubjectsListEvent) {
        when (event) {
            is SubjectsListEvent.DeleteSubject -> {
                deleteSubject(event.subject)
            }
        }
    }

    private fun loadSubjects() {
        _state.update { it.copy(isLoading = true) }
        getAllSubjectsUseCase()
            .onEach { subjects ->
                _state.update {
                    it.copy(
                        subjects = subjects,
                        isLoading = false,
                        error = null
                    )
                }
            }
            .catch { error ->
                _state.update {
                    it.copy(
                        isLoading = false,
                        error = error.message
                    )
                }
            }
            .launchIn(viewModelScope)
    }

    private fun deleteSubject(subject: Subject) {
        viewModelScope.launch {
            try {
                subjectRepository.deleteSubject(subject)

            } catch (e: Exception) {
                _state.update { it.copy(error = "Error al eliminar la asignatura: ${e.message}") }
            }
        }
    }
} 