package com.example.todokmp.android

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.todokmp.db.TodoEntity
import com.example.todokmp.db.TodoRepository
import com.example.todokmp.model.Priority
import com.example.todokmp.model.TodoFilter
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class TodoViewModel(private val repository: TodoRepository) : ViewModel() {

    private val _filter = MutableStateFlow(TodoFilter.ALL)
    val filter: StateFlow<TodoFilter> = _filter.asStateFlow()

    private val _showForm = MutableStateFlow(false)
    val showForm: StateFlow<Boolean> = _showForm.asStateFlow()

    private val _editingTodo = MutableStateFlow<TodoEntity?>(null)
    val editingTodo: StateFlow<TodoEntity?> = _editingTodo.asStateFlow()

    private val todos: Flow<List<TodoEntity>> = repository.getAllTodos()

    val filteredTodos: StateFlow<List<TodoEntity>> = combine(todos, _filter) { list, f ->
        when (f) {
            TodoFilter.ALL -> list
            TodoFilter.ACTIVE -> list.filter { !it.completed }
            TodoFilter.DONE -> list.filter { it.completed }
        }
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    val counts: StateFlow<Map<TodoFilter, Int>> = todos.map { list ->
        mapOf(
            TodoFilter.ALL to list.size,
            TodoFilter.ACTIVE to list.count { !it.completed },
            TodoFilter.DONE to list.count { it.completed }
        )
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyMap())

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

    fun showAddForm() {
        _editingTodo.value = null
        _showForm.value = true
    }

    fun showEditForm(todo: TodoEntity) {
        _editingTodo.value = todo
        _showForm.value = true
    }

    fun dismissForm() {
        _showForm.value = false
        _editingTodo.value = null
    }

    fun addTodo(title: String, category: String, priority: Priority) {
        viewModelScope.launch {
            repository.addTodo(title, category, priority)
        }
        dismissForm()
    }

    fun updateTodo(id: Long, title: String, category: String, priority: Priority) {
        viewModelScope.launch {
            repository.updateTodo(id, title, category, priority)
        }
        dismissForm()
    }

    fun toggleTodo(todo: TodoEntity) {
        viewModelScope.launch {
            repository.toggleTodo(todo.id, !todo.completed)
        }
    }

    fun deleteTodo(todo: TodoEntity) {
        viewModelScope.launch {
            repository.deleteTodo(todo.id)
        }
    }
}
