package com.seven.ikar.kotlin.feature.privacy

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.model.PrivacySettingsDto
import com.seven.ikar.kotlin.core.model.UpdatePrivacySettingsRequest
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class PrivacySecurityUiState(
    val settings: PrivacySettingsDto? = null,
    val isLoading: Boolean = false,
    val isSaving: Boolean = false,
    val errorMessage: String? = null
)

class PrivacySecurityViewModel(private val container: AppContainer) : ViewModel() {
    private val _uiState = MutableStateFlow(PrivacySecurityUiState())
    val uiState: StateFlow<PrivacySecurityUiState> = _uiState.asStateFlow()

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            runCatching {
                container.executeAuthorized { session ->
                    container.apiClient.getMyPrivacySettings(session.accessToken)
                }
            }.onSuccess { settings ->
                container.privacyRuntimeSettings.saveFrom(settings)
                _uiState.value = _uiState.value.copy(settings = settings, isLoading = false)
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(isLoading = false, errorMessage = error.message)
            }
        }
    }

    fun update(transform: (PrivacySettingsDto) -> PrivacySettingsDto) {
        val current = _uiState.value.settings ?: return
        val next = transform(current)
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(settings = next, isSaving = true, errorMessage = null)
            runCatching {
                container.executeAuthorized { session ->
                    container.apiClient.updateMyPrivacySettings(
                        session.accessToken,
                        UpdatePrivacySettingsRequest(
                            phoneNumberVisibility = next.phoneNumberVisibility,
                            lastSeenVisibility = next.lastSeenVisibility,
                            profilePhotoVisibility = next.profilePhotoVisibility,
                            blockedUserIds = next.blockedUserIds,
                            alwaysAllowUserIds = next.alwaysAllowUserIds,
                            neverAllowUserIds = next.neverAllowUserIds,
                            passcodeLockEnabled = next.passcodeLockEnabled,
                            showMessagePreview = next.showMessagePreview
                        )
                    )
                }
            }.onSuccess { saved ->
                container.privacyRuntimeSettings.saveFrom(saved)
                _uiState.value = _uiState.value.copy(settings = saved, isSaving = false)
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(settings = current, isSaving = false, errorMessage = error.message)
            }
        }
    }
}

internal fun nextVisibility(value: String): String = when (value) {
    "everyone" -> "contacts"
    "contacts" -> "nobody"
    else -> "everyone"
}
