package com.placeholder.sherpai2.ui.collections

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.placeholder.sherpai2.data.local.entity.CollectionEntity
import com.placeholder.sherpai2.data.repository.CollectionRepository
import com.placeholder.sherpai2.ui.search.DateRange
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * CollectionsViewModel - Manages collections list and creation
 */
@HiltViewModel
class CollectionsViewModel @Inject constructor(
    private val collectionRepository: CollectionRepository
) : ViewModel() {

    // All collections
    val collections: StateFlow<List<CollectionEntity>> = collectionRepository
        .getAllCollections()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )

    // UI state for creation dialog
    private val _creationState = MutableStateFlow<CreationState>(CreationState.None)
    val creationState: StateFlow<CreationState> = _creationState.asStateFlow()

    // ==========================================
    // COLLECTION CREATION
    // ==========================================

    fun startSmartCollectionFromSearch(
        includedPeople: Set<String>,
        excludedPeople: Set<String>,
        includedTags: Set<String>,
        excludedTags: Set<String>,
        dateRange: DateRange,
        photoCount: Int
    ) {
        _creationState.value = CreationState.SmartFromSearch(
            includedPeople = includedPeople,
            excludedPeople = excludedPeople,
            includedTags = includedTags,
            excludedTags = excludedTags,
            dateRange = dateRange,
            photoCount = photoCount
        )
    }

    fun startStaticCollectionFromImages(imageIds: List<String>) {
        _creationState.value = CreationState.StaticFromImages(
            imageIds = imageIds,
            photoCount = imageIds.size
        )
    }

    fun cancelCreation() {
        _creationState.value = CreationState.None
    }

    fun createSmartCollection(name: String, description: String?) {
        val state = _creationState.value as? CreationState.SmartFromSearch ?: return

        viewModelScope.launch {
            collectionRepository.createSmartCollection(
                name = name,
                description = description,
                includedPeople = state.includedPeople,
                excludedPeople = state.excludedPeople,
                includedTags = state.includedTags,
                excludedTags = state.excludedTags,
                dateRange = state.dateRange
            )

            _creationState.value = CreationState.None
        }
    }

    fun createStaticCollection(name: String, description: String?) {
        val state = _creationState.value as? CreationState.StaticFromImages ?: return

        viewModelScope.launch {
            collectionRepository.createStaticCollection(
                name = name,
                description = description,
                imageIds = state.imageIds
            )

            _creationState.value = CreationState.None
        }
    }

    // ==========================================
    // COLLECTION MANAGEMENT
    // ==========================================

    fun deleteCollection(collectionId: String) {
        viewModelScope.launch {
            collectionRepository.deleteCollection(collectionId)
        }
    }

    fun togglePinned(collectionId: String) {
        viewModelScope.launch {
            collectionRepository.togglePinned(collectionId)
        }
    }

    fun refreshSmartCollections() {
        viewModelScope.launch {
            collectionRepository.evaluateAllSmartCollections()
        }
    }

    // ==========================================
    // STATISTICS
    // ==========================================

    fun getCollectionSummary(): String {
        val count = collections.value.size
        val smartCount = collections.value.count { it.type == "SMART" }
        val staticCount = collections.value.count { it.type == "STATIC" }

        return when {
            count == 0 -> "No collections yet"
            smartCount > 0 && staticCount > 0 -> "$smartCount smart • $staticCount static"
            smartCount > 0 -> "$smartCount smart collections"
            staticCount > 0 -> "$staticCount static collections"
            else -> "$count collections"
        }
    }
}

/**
 * Creation state for dialogs
 */
sealed class CreationState {
    object None : CreationState()

    data class SmartFromSearch(
        val includedPeople: Set<String>,
        val excludedPeople: Set<String>,
        val includedTags: Set<String>,
        val excludedTags: Set<String>,
        val dateRange: DateRange,
        val photoCount: Int
    ) : CreationState()

    data class StaticFromImages(
        val imageIds: List<String>,
        val photoCount: Int
    ) : CreationState()
}