package com.apps.pixwall.data

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apps.pixwall.IApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class MainViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: PaperRepository by lazy {
        val dao = AppDataBase.getDatabase(application).paperDao()
        PaperRepository(dao)
    }

    // 防抖控制
    private var lastSearchTime = 0L
    private var lastQuery: String? = null
    private val searchDebounceTime = 500L

    // LiveData 统一暴露
    private val _paperResult = MutableLiveData<Paper?>() // id查询结果
    val paperResult: LiveData<Paper?> get() = _paperResult

    private val _categoryList = MutableLiveData<List<Paper>>(emptyList()) // 类别列表
    val categoryList: LiveData<List<Paper>> get() = _categoryList

    private val _coverMap = MutableLiveData<Map<String, List<Paper>>>(emptyMap()) // 封面分类映射
    val coverMap: LiveData<Map<String, List<Paper>>> get() = _coverMap

    private val _loadingState = MutableLiveData(false) // 加载状态
    val loadingState: LiveData<Boolean> get() = _loadingState

    private val _searchList = MutableLiveData<List<Paper>>(emptyList()) // 搜索结果
    val searchList: LiveData<List<Paper>> get() = _searchList

    private val _isLiked = MutableLiveData<Boolean?>() // 是否收藏
    val isLiked: LiveData<Boolean?> get() = _isLiked

    val likePapers: LiveData<List<Paper>> get() = repository.getLikes()

    fun debugDatabase() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val papers = repository.allPaper()
                Log.d("DB_DEBUG", "总记录数: ${papers.size}")
                papers.take(5).forEach { paper ->
                    Log.d("DB_DEBUG", "Paper[${paper.id}]: " +
                            "cat=${paper.categoryName}, " +
                            "imId=${paper.imId}, " +
                            "desc=${paper.description.take(10)}...")
                }
            } catch (e: Exception) {
                Log.e("DB_DEBUG", "查询失败", e)
            }
        }
    }

    fun updatePaper(paper: Paper) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updatePaper(paper)
        }
    }

    fun getPaperResult(id: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _paperResult.postValue(repository.getPaperById(id))
        }
    }

    fun getCategoryList(name: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _categoryList.postValue(repository.getPaperByCategory(name))
        }
    }

    fun loadAllCategoryCovers() {
        if (_loadingState.value == true) return

        viewModelScope.launch(Dispatchers.IO) {
            _loadingState.postValue(true)
            val categoryList = IApplication.categoryList
            val resultMap = mutableMapOf<String, List<Paper>>()

            val deferredList = categoryList.map { category ->
                async {
                    try {
                        category to repository.getCategoryCover(category)
                    } catch (e: Exception) {
                        Log.e("BatchLoad", "加载分类[$category]失败: ${e.message}")
                        category to emptyList<Paper>()
                    }
                }
            }

            deferredList.awaitAll().forEach { (category, papers) ->
                resultMap[category] = papers
            }

            _coverMap.postValue(resultMap)
            _loadingState.postValue(false)
            Log.d("BatchLoad", "所有分类封面数据加载完成")
        }
    }

    fun getSearchList(query: String) {
        val currentTime = System.currentTimeMillis()
        if (query == lastQuery && (currentTime - lastSearchTime) < searchDebounceTime) {
            return
        }
        lastQuery = query
        lastSearchTime = currentTime

        viewModelScope.launch(Dispatchers.IO) {
            try {
                _searchList.postValue(repository.searchByKey(query))
            } catch (e: Exception) {
                _searchList.postValue(emptyList())
                Log.e("Search", "Search failed", e)
            }
        }
    }

    fun checkLike(id: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _isLiked.postValue(repository.isLike(id))
        }
    }

    fun setLike(paper: Paper) {
        viewModelScope.launch(Dispatchers.IO) {
            val updatePaper = paper.copy(isLike = !paper.isLike)
            repository.updatePaper(updatePaper)
            Log.d("setlike status",updatePaper.isLike.toString())
            _isLiked.postValue(updatePaper.isLike)
        }
    }
}