package com.safecheckin.app.ui.screens.settings

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.safecheckin.app.data.repository.CloudRepository
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

data class SettingsUiState(
    val gracePeriodHours: Int = 24,
    val gracePeriodMinutes: Int = 0,
    val presetMessage: String = "如果你收到这条消息，说明我可能出事了，请尽快联系我或报警。",
    val serverUrl: String = "http://localhost:8000",
    val dailyReminder: Boolean = true,
    val isLoading: Boolean = false,
    val isSaving: Boolean = false,
    val saveSuccess: Boolean = false,
    val errorMessage: String? = null,
    val successMessage: String? = null
)

/**
 * v1: 设置页全量走云端
 * - 进入页面从云端拉取宽限期和预设消息
 * - 保存时上传至云端，服务器地址保存在本地 DataStore
 */
class SettingsViewModel(
    private val repository: CloudRepository
) : ViewModel() {

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

    init {
        loadSettings()
    }

    fun loadSettings() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val gracePeriod = repository.getGracePeriod()
                val presetMessage = repository.getPresetMessage()
                val dailyReminder = repository.getDailyReminder()

                // 服务器地址从本地 DataStore 读取
                repository.getBaseUrl().collect { url ->
                    _uiState.update {
                        it.copy(
                            gracePeriodHours = gracePeriod.first,
                            gracePeriodMinutes = gracePeriod.second,
                            presetMessage = presetMessage,
                            serverUrl = url,
                            dailyReminder = dailyReminder,
                            isLoading = false,
                            errorMessage = null
                        )
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.update { it.copy(isLoading = false, errorMessage = "加载设置失败: ${e.message}") }
            }
        }
    }

    fun updateGracePeriodHours(hours: Int) {
        _uiState.update { it.copy(gracePeriodHours = hours, saveSuccess = false, errorMessage = null) }
    }

    fun updateGracePeriodMinutes(minutes: Int) {
        _uiState.update { it.copy(gracePeriodMinutes = minutes, saveSuccess = false, errorMessage = null) }
    }

    fun updatePresetMessage(message: String) {
        _uiState.update { it.copy(presetMessage = message, saveSuccess = false, errorMessage = null) }
    }

    fun updateDailyReminder(enabled: Boolean) {
        viewModelScope.launch {
            val success = repository.setDailyReminder(enabled)
            if (success) {
                _uiState.update { it.copy(dailyReminder = enabled, successMessage = if (enabled) "已开启每日提醒" else "已关闭每日提醒") }
            } else {
                _uiState.update { it.copy(errorMessage = "设置提醒失败") }
            }
        }
    }

    fun deleteAccount(onSuccess: () -> Unit) {
        viewModelScope.launch {
            _uiState.update { it.copy(isSaving = true, errorMessage = null) }
            try {
                val success = repository.deleteAccount()
                if (success) {
                    repository.clearLoginState()
                    _uiState.update { it.copy(isSaving = false) }
                    onSuccess()
                } else {
                    _uiState.update { it.copy(isSaving = false, errorMessage = "注销失败，请稍后重试") }
                }
            } catch (e: Exception) {
                _uiState.update { it.copy(isSaving = false, errorMessage = "注销失败: ${e.message}") }
            }
        }
    }

    fun updateServerUrl(url: String) {
        _uiState.update { it.copy(serverUrl = url, saveSuccess = false, errorMessage = null) }
    }

    /**
     * 保存设置：宽限期和预设消息上传云端，服务器地址保存本地
     */
    fun saveSettings() {
        val state = _uiState.value

        if (state.gracePeriodHours < 0 || state.gracePeriodMinutes < 0) {
            _uiState.update { it.copy(errorMessage = "宽限期不能为负数") }
            return
        }
        if (state.gracePeriodHours == 0 && state.gracePeriodMinutes == 0) {
            _uiState.update { it.copy(errorMessage = "宽限期不能为0") }
            return
        }
        if (state.presetMessage.isBlank()) {
            _uiState.update { it.copy(errorMessage = "预设消息不能为空") }
            return
        }
        if (state.serverUrl.isBlank() || !state.serverUrl.startsWith("http")) {
            _uiState.update { it.copy(errorMessage = "请输入有效的服务器地址（以 http 开头）") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isSaving = true, errorMessage = null, successMessage = null) }
            try {
                var errorMsg = ""

                // 上传宽限期到云端
                val graceSuccess = repository.setGracePeriod(state.gracePeriodHours, state.gracePeriodMinutes)
                if (!graceSuccess) errorMsg += "保存宽限期失败; "

                // 上传预设消息到云端
                val presetSuccess = repository.setPresetMessage(state.presetMessage)
                if (!presetSuccess) errorMsg += "保存预设消息失败; "

                // 服务器地址保存到本地
                repository.setBaseUrl(state.serverUrl)

                if (errorMsg.isEmpty()) {
                    _uiState.update {
                        it.copy(isSaving = false, saveSuccess = true, successMessage = "设置已保存到云端")
                    }
                } else {
                    _uiState.update {
                        it.copy(isSaving = false, saveSuccess = false, errorMessage = errorMsg.trimEnd(';', ' '))
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.update {
                    it.copy(isSaving = false, saveSuccess = false, errorMessage = "保存设置失败: ${e.message}")
                }
            }
        }
    }

    fun clearMessages() {
        _uiState.update { it.copy(errorMessage = null, successMessage = null, saveSuccess = false) }
    }

    fun logout() {
        viewModelScope.launch {
            repository.clearLoginState()
        }
    }

    class Factory(private val context: Context) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return SettingsViewModel(CloudRepository(context)) as T
        }
    }
}
