package com.design.wallpapergallery.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.design.wallpapergallery.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: PhotoRepository by lazy {
        val dao = AppDataBase.getDatabase(application).photoDao()
        PhotoRepository(dao)
    }

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

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

    private val _classificationList = MutableLiveData<List<Photo>>(emptyList()) // 类别列表
    val classificationList: LiveData<List<Photo>> get() = _classificationList

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

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

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

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

    val likePhotos: LiveData<List<Photo>> get() = repository.getLikes()
    // 添加标题存储
    var currentTitleName: String? = null

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

    fun updatePhoto(paper: Photo) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updatePhoto(paper)
        }
    }

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

    fun getClassificationList(name: String) {
        viewModelScope.launch(Dispatchers.IO) {
            _classificationList.postValue(repository.getPhotoByClassification(name))
        }
    }

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

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

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

            deferredList.awaitAll().forEach { (classification, photos) ->
                resultMap[classification] = photos
            }

            _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: Photo) {
        viewModelScope.launch(Dispatchers.IO) {
            val updatePhoto = paper.copy(isLike = !paper.isLike)
            repository.updatePhoto(updatePhoto)
            Log.d("setlike status",updatePhoto.isLike.toString())
            _isLiked.postValue(updatePhoto.isLike)
        }
    }
}