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

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.domain.model.Subject
import com.diegocayo.organizame.domain.usecase.SaveSubjectUseCase
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.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CreateSubjectViewModel @Inject constructor(
    private val saveSubjectUseCase: SaveSubjectUseCase
) : ViewModel() {

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

    fun onEvent(event: CreateSubjectEvent) {
        when (event) {
            is CreateSubjectEvent.OnNameChange -> {
                _state.update { it.copy(name = event.name) }
                validateForm()
            }

            is CreateSubjectEvent.OnAbbreviationChange -> {
                _state.update { it.copy(abbreviation = event.abbreviation) }
                validateForm()
            }

            is CreateSubjectEvent.OnColorChange -> {
                _state.update { it.copy(color = event.color) }
                validateForm()
            }

            CreateSubjectEvent.OnSubmit -> saveSubject()
        }
    }

    private fun validateForm() {
        val currentState = _state.value
        val isValid = currentState.name.isNotBlank() &&
                currentState.abbreviation.isNotBlank() &&
                currentState.color != 0

        _state.update { it.copy(isFormValid = isValid) }
    }

    private fun saveSubject() {
        viewModelScope.launch {
            val currentState = state.value

            if (!currentState.isFormValid) {
                _state.update {
                    it.copy(error = "Por favor, complete todos los campos requeridos")
                }
                return@launch
            }

            _state.update { it.copy(isLoading = true, error = null) }
            try {
                val subject = Subject(
                    name = currentState.name,
                    abbreviation = currentState.abbreviation,
                    color = currentState.color
                )
                saveSubjectUseCase(subject)
                _state.update { it.copy(isSuccess = true) }
            } catch (e: Exception) {
                _state.update { it.copy(error = e.message) }
            } finally {
                _state.update { it.copy(isLoading = false) }
            }
        }
    }
} 