package com.radiola.ui.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.domain.model.DeeplinkService
import com.radiola.domain.model.StationTestResult
import com.radiola.domain.repository.SettingsRepository
import com.radiola.domain.usecase.TestStationsUseCase
import com.radiola.domain.usecase.auth.GetAuthStateUseCase
import com.radiola.domain.usecase.auth.GetCurrentUserUseCase
import com.radiola.domain.usecase.auth.LogoutUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
    private val testStationsUseCase: TestStationsUseCase,
    getAuthStateUseCase: GetAuthStateUseCase,
    getCurrentUserUseCase: GetCurrentUserUseCase,
    private val logoutUseCase: LogoutUseCase
) : ViewModel() {

    val sleepTimerMinutes: StateFlow<Int> = settingsRepository.getSleepTimerMinutes()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 30)

    val enabledServices: StateFlow<Set<String>> = settingsRepository.getEnabledDeeplinkServices()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptySet())

    val equalizerPreset: StateFlow<String> = settingsRepository.getEqualizerPreset()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "Flat")

    val visualizerStyle: StateFlow<String> = settingsRepository.getVisualizerStyle()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "bars_center")

    val themePalette: StateFlow<String> = settingsRepository.getThemePalette()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), "forest")

    val isRecordingEnabled: StateFlow<Boolean> = settingsRepository.isRecordingEnabled()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)

    // Предпочитаемый битрейт по умолчанию (0 = авто/станция сама выбирает).
    val preferredBitrate: StateFlow<Int> = settingsRepository.getPreferredBitrate()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0)

    val isLoggedIn: StateFlow<Boolean> = getAuthStateUseCase()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)

    val currentUser = getCurrentUserUseCase()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)

    private val _isTesting = MutableStateFlow(false)
    val isTesting: StateFlow<Boolean> = _isTesting.asStateFlow()

    private val _testProgress = MutableStateFlow(0)
    val testProgress: StateFlow<Int> = _testProgress.asStateFlow()

    private val _testTotal = MutableStateFlow(0)
    val testTotal: StateFlow<Int> = _testTotal.asStateFlow()

    private val _testResults = MutableStateFlow<List<StationTestResult>>(emptyList())
    val testResults: StateFlow<List<StationTestResult>> = _testResults.asStateFlow()

    fun setSleepTimer(minutes: Int) {
        viewModelScope.launch { settingsRepository.setSleepTimerMinutes(minutes) }
    }

    fun setPreferredBitrate(bitrate: Int) {
        viewModelScope.launch { settingsRepository.setPreferredBitrate(bitrate) }
    }

    fun toggleService(serviceId: String, enabled: Boolean) {
        viewModelScope.launch {
            val current = enabledServices.value.toMutableSet()
            if (enabled) current.add(serviceId) else current.remove(serviceId)
            settingsRepository.setEnabledDeeplinkServices(current)
        }
    }

    fun setEqualizerPreset(preset: String) {
        viewModelScope.launch { settingsRepository.setEqualizerPreset(preset) }
    }

    fun setVisualizerStyle(style: String) {
        viewModelScope.launch { settingsRepository.setVisualizerStyle(style) }
    }

    fun setThemePalette(id: String) {
        viewModelScope.launch { settingsRepository.setThemePalette(id) }
    }

    fun setRecordingEnabled(enabled: Boolean) {
        viewModelScope.launch { settingsRepository.setRecordingEnabled(enabled) }
    }

    fun startTesting() {
        viewModelScope.launch {
            _isTesting.value = true
            _testProgress.value = 0
            _testTotal.value = 0
            _testResults.value = emptyList()

            val results = mutableListOf<StationTestResult>()
            testStationsUseCase().collect { progress ->
                _testProgress.value = progress.current
                _testTotal.value = progress.total
                progress.result?.let { results.add(it) }
            }
            _testResults.value = results
            _isTesting.value = false
        }
    }

    fun clearTestResults() {
        _testResults.value = emptyList()
    }

    fun logout() {
        viewModelScope.launch { logoutUseCase() }
    }
}
