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

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.domain.model.Event
import com.diegocayo.organizame.domain.repository.EventRepository
import com.diegocayo.organizame.domain.repository.SubjectRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CreateEventViewModel @Inject constructor(
    private val eventRepository: EventRepository,
    private val subjectRepository: SubjectRepository
) : ViewModel() {

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

    init {
        loadSubjects()
    }

    private fun loadSubjects() {
        viewModelScope.launch {
            try {
                subjectRepository.getAllSubjects().collect { subjects ->
                    _state.value = _state.value.copy(subjects = subjects)
                }
            } catch (e: Exception) {
                _state.value = _state.value.copy(error = e.message)
            }
        }
    }

    fun onEvent(event: CreateEventEvent) {
        when (event) {
            is CreateEventEvent.OnTitleChange -> {
                _state.value = _state.value.copy(title = event.title)
                validateForm()
            }

            is CreateEventEvent.OnDescriptionChange -> {
                _state.value = _state.value.copy(description = event.description)
                validateForm()
            }

            is CreateEventEvent.OnSubjectSelect -> {
                _state.value = _state.value.copy(selectedSubject = event.subject)
                validateForm()
            }

            is CreateEventEvent.OnDateSelect -> {
                _state.value = _state.value.copy(
                    date = event.timestamp,
                    showDatePicker = false
                )
                validateForm()
            }

            is CreateEventEvent.OnStartTimeSelect -> {
                _state.value = _state.value.copy(
                    startTime = event.timestamp,
                    showStartTimePicker = false
                )
                validateForm()
            }

            is CreateEventEvent.OnEndTimeSelect -> {
                _state.value = _state.value.copy(
                    endTime = event.timestamp,
                    showEndTimePicker = false
                )
                validateForm()
            }

            is CreateEventEvent.OnShowDatePicker -> {
                _state.value = _state.value.copy(showDatePicker = true)
            }

            is CreateEventEvent.OnShowStartTimePicker -> {
                _state.value = _state.value.copy(showStartTimePicker = true)
            }

            is CreateEventEvent.OnShowEndTimePicker -> {
                _state.value = _state.value.copy(showEndTimePicker = true)
            }

            is CreateEventEvent.OnHideDatePicker -> {
                _state.value = _state.value.copy(showDatePicker = false)
            }

            is CreateEventEvent.OnHideStartTimePicker -> {
                _state.value = _state.value.copy(showStartTimePicker = false)
            }

            is CreateEventEvent.OnHideEndTimePicker -> {
                _state.value = _state.value.copy(showEndTimePicker = false)
            }

            is CreateEventEvent.OnCreateEvent -> createEvent()
        }
    }

    private fun validateForm() {
        val currentState = _state.value
        val isValid = currentState.title.isNotBlank() &&
                currentState.description.isNotBlank() &&
                currentState.startTime < currentState.endTime

        _state.value = currentState.copy(isFormValid = isValid)
    }

    private fun createEvent() {
        val currentState = _state.value

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

        if (currentState.startTime >= currentState.endTime) {
            _state.value =
                currentState.copy(error = "La hora de inicio debe ser anterior a la hora de fin")
            return
        }

        viewModelScope.launch {
            _state.value = currentState.copy(isLoading = true)
            try {
                val event = Event(
                    title = currentState.title,
                    description = currentState.description,
                    subject = currentState.selectedSubject,
                    date = currentState.date,
                    startTime = currentState.startTime,
                    endTime = currentState.endTime,
                    createdAt = System.currentTimeMillis()
                )
                eventRepository.insertEvent(event)
                _state.value = currentState.copy(
                    isLoading = false,
                    isEventCreated = true
                )
            } catch (e: Exception) {
                _state.value = currentState.copy(
                    isLoading = false,
                    error = e.message
                )
            }
        }
    }
} 