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

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.data.local.entity.TaskStatus
import com.diegocayo.organizame.domain.model.Task
import com.diegocayo.organizame.domain.repository.SubjectRepository
import com.diegocayo.organizame.domain.repository.TaskRepository
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 CreateTaskViewModel @Inject constructor(
    private val taskRepository: TaskRepository,
    private val subjectRepository: SubjectRepository
) : ViewModel() {

    private val _state = MutableStateFlow(CreateTaskState())
    val state: StateFlow<CreateTaskState> = _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: CreateTaskEvent) {
        when (event) {
            is CreateTaskEvent.OnTitleChange -> {
                _state.value = _state.value.copy(
                    title = event.title,
                    error = null
                )
                validateForm()
            }

            is CreateTaskEvent.OnDescriptionChange -> {
                _state.value = _state.value.copy(
                    description = event.description,
                    error = null
                )
                validateForm()
            }

            is CreateTaskEvent.OnSubjectSelect -> {
                _state.value = _state.value.copy(
                    selectedSubject = event.subject,
                    error = null
                )
                validateForm()
            }

            is CreateTaskEvent.OnPrioritySelect -> {
                _state.value = _state.value.copy(priority = event.priority)
            }

            is CreateTaskEvent.OnDateSelect -> {
                _state.value = _state.value.copy(
                    scheduledDate = event.timestamp,
                    showDatePicker = false
                )
            }

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

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

            is CreateTaskEvent.OnCreateTask -> createTask()
        }
    }

    private fun validateForm() {
        val currentState = _state.value
        val isValid = currentState.title.isNotBlank() &&
                currentState.description.isNotBlank()
        
        _state.value = currentState.copy(isFormValid = isValid)
    }

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

        if (currentState.title.isBlank()) {
            _state.value = currentState.copy(error = "El título es obligatorio")
            return
        }

        if (currentState.description.isBlank()) {
            _state.value = currentState.copy(error = "La descripción es obligatoria")
            return
        }

        viewModelScope.launch {
            _state.value = currentState.copy(isLoading = true)
            try {
                val task = Task(
                    title = currentState.title,
                    description = currentState.description,
                    subject = currentState.selectedSubject,
                    priority = currentState.priority,
                    status = TaskStatus.PENDING,
                    scheduledDate = currentState.scheduledDate,
                    createdAt = System.currentTimeMillis()
                )
                taskRepository.insertTask(task)
                _state.value = currentState.copy(
                    isLoading = false,
                    isTaskCreated = true
                )
            } catch (e: Exception) {
                _state.value = currentState.copy(
                    isLoading = false,
                    error = e.message
                )
            }
        }
    }
} 