package com.example.todokotlin

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.todokotlin.data.Todo
import com.example.todokotlin.data.TodoDatabase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

enum class TodoFilter { All, Active, Done }

data class TodoUiState(
    val todos: List<Todo> = emptyList(),
    val filter: TodoFilter = TodoFilter.All,
    val allCount: Int = 0,
    val activeCount: Int = 0,
    val doneCount: Int = 0
)

class TodoViewModel(application: Application) : AndroidViewModel(application) {
    private val dao = TodoDatabase.getDatabase(application).todoDao()
    private val _filter = MutableStateFlow(TodoFilter.All)

    val uiState: StateFlow<TodoUiState> = combine(
        dao.getAllTodos(),
        _filter
    ) { todos, filter ->
        val filtered = when (filter) {
            TodoFilter.All -> todos
            TodoFilter.Active -> todos.filter { !it.completed }
            TodoFilter.Done -> todos.filter { it.completed }
        }
        TodoUiState(
            todos = filtered,
            filter = filter,
            allCount = todos.size,
            activeCount = todos.count { !it.completed },
            doneCount = todos.count { it.completed }
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = TodoUiState()
    )

    fun setFilter(filter: TodoFilter) {
        _filter.value = filter
    }

    fun addTodo(title: String, category: String, priority: String) {
        viewModelScope.launch {
            dao.insert(
                Todo(
                    title = title,
                    category = category,
                    priority = priority
                )
            )
        }
    }

    fun updateTodo(todo: Todo) {
        viewModelScope.launch {
            dao.update(todo)
        }
    }

    fun toggleCompleted(todo: Todo) {
        viewModelScope.launch {
            dao.update(todo.copy(completed = !todo.completed))
        }
    }

    fun deleteTodo(todo: Todo) {
        viewModelScope.launch {
            dao.delete(todo)
        }
    }
}
