import Foundation
import SwiftUI

@Observable
final class TodoViewModel {
    var todos: [Todo] = []
    var currentFilter: TodoFilter = .all

    // MARK: - Computed Properties

    var filteredTodos: [Todo] {
        switch currentFilter {
        case .all:
            return todos
        case .active:
            return todos.filter { !$0.completed }
        case .done:
            return todos.filter { $0.completed }
        }
    }

    var allCount: Int {
        todos.count
    }

    var activeCount: Int {
        todos.filter { !$0.completed }.count
    }

    var doneCount: Int {
        todos.filter { $0.completed }.count
    }

    func count(for filter: TodoFilter) -> Int {
        switch filter {
        case .all: return allCount
        case .active: return activeCount
        case .done: return doneCount
        }
    }

    // MARK: - Initialization

    init() {
        loadTodos()
    }

    // MARK: - Actions

    func loadTodos() {
        todos = DatabaseManager.shared.loadTodos()
    }

    func addTodo(title: String, category: String, priority: Priority) {
        if let todo = DatabaseManager.shared.insertTodo(title: title, category: category, priority: priority) {
            todos.insert(todo, at: 0)
        }
    }

    func updateTodo(id: Int64, title: String, category: String, priority: Priority) {
        DatabaseManager.shared.updateTodo(id: id, title: title, category: category, priority: priority)
        if let index = todos.firstIndex(where: { $0.id == id }) {
            todos[index].title = title
            todos[index].category = category
            todos[index].priority = priority
        }
    }

    func toggleTodo(id: Int64) {
        if let index = todos.firstIndex(where: { $0.id == id }) {
            todos[index].completed.toggle()
            DatabaseManager.shared.toggleTodo(id: id, completed: todos[index].completed)
        }
    }

    func deleteTodo(id: Int64) {
        DatabaseManager.shared.deleteTodo(id: id)
        todos.removeAll { $0.id == id }
    }

    func setFilter(_ filter: TodoFilter) {
        currentFilter = filter
    }
}
