package com.rosetta.messenger.ui.chats.attach

import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
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 AttachAlertViewModel(application: Application) : AndroidViewModel(application) {

    private val _uiState = MutableStateFlow(AttachAlertUiState())
    val uiState: StateFlow<AttachAlertUiState> = _uiState.asStateFlow()

    fun loadMedia(context: Context) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            val data = loadMediaPickerData(context)
            _uiState.update {
                it.copy(
                    mediaItems = data.items,
                    albums = data.albums,
                    selectedAlbumId = data.albums.firstOrNull()?.id ?: ALL_MEDIA_ALBUM_ID,
                    isLoading = false
                )
            }
        }
    }

    fun selectTab(tab: AttachAlertTab) {
        _uiState.update { it.copy(currentTab = tab) }
    }

    fun selectAlbum(albumId: Long) {
        _uiState.update { it.copy(selectedAlbumId = albumId) }
    }

    fun toggleSelection(itemId: Long, maxSelection: Int = 10) {
        _uiState.update { state ->
            val currentOrder = state.selectedItemOrder
            val newOrder = if (currentOrder.contains(itemId)) {
                currentOrder.filterNot { it == itemId }
            } else if (currentOrder.size < maxSelection) {
                currentOrder + itemId
            } else {
                currentOrder
            }
            state.copy(selectedItemOrder = newOrder)
        }
    }

    fun clearSelection() {
        _uiState.update { it.copy(selectedItemOrder = emptyList(), captionText = "") }
    }

    fun updateCaption(text: String) {
        _uiState.update { it.copy(captionText = text) }
    }

    fun setPermissionGranted(granted: Boolean) {
        _uiState.update { it.copy(hasPermission = granted) }
    }

    fun setEditingItem(item: MediaItem?) {
        _uiState.update { it.copy(editingItem = item) }
    }

    fun resolveSelectedMedia(): List<MediaItem> {
        val state = _uiState.value
        if (state.selectedItemOrder.isEmpty()) return emptyList()
        val byId = state.mediaItems.associateBy { it.id }
        return state.selectedItemOrder.mapNotNull { byId[it] }
    }

    fun selectionHeaderText(): String {
        val state = _uiState.value
        val count = state.selectedCount
        if (count == 0) return ""
        val byId = state.mediaItems.associateBy { it.id }
        val selected = state.selectedItemOrder.mapNotNull { byId[it] }
        val hasPhotos = selected.any { !it.isVideo }
        val hasVideos = selected.any { it.isVideo }
        return when {
            hasPhotos && hasVideos -> "$count media selected"
            hasVideos -> if (count == 1) "$count video selected" else "$count videos selected"
            else -> if (count == 1) "$count photo selected" else "$count photos selected"
        }
    }

    fun reset() {
        _uiState.value = AttachAlertUiState()
    }

    fun onShow() {
        _uiState.update {
            it.copy(
                selectedItemOrder = emptyList(),
                captionText = "",
                selectedAlbumId = ALL_MEDIA_ALBUM_ID,
                currentTab = AttachAlertTab.PHOTO,
                editingItem = null
            )
        }
    }
}
