package com.gh.gamecenter.feature.selector

import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.zhihu.matisse.internal.entity.Album
import com.zhihu.matisse.internal.entity.Item
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class LocalMediaPreviewViewModel(
    private val localMediaRepo: LocalMediaRepository,
    private val album: Album?
) : ViewModel() {

    private var highlightedItem: Item? = null
    private var _positionLiveData: MutableLiveData<Int> = MutableLiveData()
    val positionLiveData: LiveData<Int> = _positionLiveData

    private val _selectedPreviewDataListLiveData by lazy { MutableLiveData<List<SelectedPreviewData>>() }
    val selectedPreviewDataListLiveData: LiveData<List<SelectedPreviewData>> =
        _selectedPreviewDataListLiveData

    private val selectedItemList
        get() = localMediaRepo.selectedItemListFlow.value

    // 这是一个用于进入页面时已经存储选中的媒体快照列表 (仅用于 isSelectedOnly == true) 的场景
    private var selectedMediaSnapshotList: List<Item>? = null

    private val itemListFlow: StateFlow<List<Item>> = localMediaRepo.itemListFlow

    init {
        viewModelScope.launch {
            localMediaRepo.selectedItemListFlow.collect { itemList ->
                emitSelectedPreviewData(itemList)
            }
        }
    }

    fun getInitialListData(): List<Item> {
        selectedMediaSnapshotList = if (isSelectedOnly()) {
            localMediaRepo.selectedItemListFlow.value
        } else {
            itemListFlow.value
        }

        return selectedMediaSnapshotList!!
    }

    fun scrollToPosition(position: Int) {
        _positionLiveData.value = position
    }

    fun highlightItem(item: Item) {
        highlightedItem = item

        emitSelectedPreviewData(localMediaRepo.selectedItemListFlow.value)
    }

    fun findPositionInSelectedSnapshotList(uri: Uri): Int {
        return selectedMediaSnapshotList?.indexOfFirst { it.contentUri == uri } ?: 0
    }

    private fun emitSelectedPreviewData(itemList: List<Item>) {
        // Optionally modify each item
        val newSelectedPreviewDataList = arrayListOf<SelectedPreviewData>()
        for (item in itemList) {
            if (!isSelectedOnly()) {
                item.positionInAlbum = itemListFlow.value.firstOrNull {
                    it.contentUri == item.contentUri
                }?.positionInAlbum ?: -1
            }

            newSelectedPreviewDataList.add(
                SelectedPreviewData(item.contentUri == highlightedItem?.contentUri, item)
            )
        }

        // Emit the updated list
        _selectedPreviewDataListLiveData.postValue(newSelectedPreviewDataList)
    }

    fun getSelectedItem(position: Int): Item {
        return if (isSelectedOnly()) {
            selectedItemList[position]
        } else {
            itemListFlow.value[position]
        }
    }

    fun isSelectedOnly(): Boolean = album == null

    class Factory(
        private val localMediaRepo: LocalMediaRepository,
        private val album: Album?
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return LocalMediaPreviewViewModel(localMediaRepo, album) as T
        }
    }

}