package com.example.initiateaphonecallapp.ui.login

import android.os.Build
import androidx.annotation.RequiresExtension
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.model.LoginResponse
import com.example.initiateaphonecallapp.data.repository.AuthRepository
import com.example.initiateaphonecallapp.manager.PreferenceManager
import com.example.initiateaphonecallapp.manager.TokenManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class LoginViewModel( private val authRepository: AuthRepository = AuthRepository()) : ViewModel() {

    private val _loginState = MutableStateFlow(LoginState())
    val loginState: StateFlow<LoginState> = _loginState.asStateFlow()

    // 自动登录状态
    private val _autoLoginState = MutableStateFlow(AutoLoginState.IDLE)
    val autoLoginState: StateFlow<AutoLoginState> = _autoLoginState

    // 记住我和自动登录状态
    var rememberMe = MutableStateFlow(false)
    var autoLogin = MutableStateFlow(false)

    enum class AutoLoginState {
        IDLE, CHECKING, SUCCESS, FAILED
    }

    init {
        // 应用启动时检查自动登录
        checkAutoLogin()
    }

    fun onUsernameChange(username: String) {
        _loginState.value = _loginState.value.copy(
            username = username,
            errorMessage = ""
        )
    }

    fun onPasswordChange(password: String) {
        _loginState.value = _loginState.value.copy(
            password = password,
            errorMessage = ""
        )
    }

    fun onRememberMeChange(remember: Boolean) {
        rememberMe.value = remember
        // 如果取消记住我，也取消自动登录
        if (!remember) {
            autoLogin.value = false
        }
    }

    fun onAutoLoginChange(auto: Boolean) {
        autoLogin.value = auto
        // 如果启用自动登录，必须启用记住我
        if (auto) {
            rememberMe.value = true
        }
    }

    // 检查自动登录
    private fun checkAutoLogin() {
        viewModelScope.launch {
            // 检查是否启用了自动登录且有保存的 token
            if (PreferenceManager.isAutoLogin() && PreferenceManager.hasValidToken()) {
                _autoLoginState.value = AutoLoginState.CHECKING
                println("🔐 LoginViewModel: 开始自动登录")

                // 从存储中获取用户名
                val savedUsername = PreferenceManager.getSavedUsername()

                // 填充用户名到登录状态
                _loginState.value = _loginState.value.copy(username = savedUsername)

                // 恢复 token
                PreferenceManager.restoreToken()

                // 模拟自动登录过程
                kotlinx.coroutines.delay(1000)

                // 自动登录成功
                _loginState.value = _loginState.value.copy(
                    isLoginSuccess = true,
                    authToken = TokenManager.getToken()
                )
                _autoLoginState.value = AutoLoginState.SUCCESS
                println("✅ LoginViewModel: 自动登录成功")

            } else {
                // 如果只是记住我，填充用户名
                if (PreferenceManager.isRememberMe()) {
                    val savedUsername = PreferenceManager.getSavedUsername()
                    _loginState.value = _loginState.value.copy(username = savedUsername)
                }
                _autoLoginState.value = AutoLoginState.IDLE
            }
        }
    }

    fun login() {
        val currentState = _loginState.value

        if (currentState.username.isEmpty() || currentState.password.isEmpty()) {
            _loginState.value = currentState.copy(
                errorMessage = "请填写账号和密码"
            )
            return
        }

        _loginState.value = currentState.copy(
            isLoading = true,
            errorMessage = ""
        )

        viewModelScope.launch {
            // 模拟网络请求
            val result = authRepository.login(
                username = currentState.username,
                password = currentState.password
            )

            result.fold(
                onSuccess = { loginResponse ->
                    if (loginResponse.code==200) {
                        // 登录成功
                        _loginState.value = currentState.copy(
                            isLoading = false,
                            isLoginSuccess = true,
                            authToken = loginResponse.token,
                            errorMessage = ""
                        )

                        // 保存登录信息
                        loginResponse.token?.let {
                            PreferenceManager.saveLoginInfo(
                                username = currentState.username,
                                password = currentState.password,
                                token = it,
                                rememberMe = rememberMe.value,
                                autoLogin = autoLogin.value
                            )
                        }

                        TokenManager.setToken(loginResponse.token!!)

                    } else {
                        // 登录失败（服务器返回成功但业务逻辑失败）
                        _loginState.value = currentState.copy(
                            isLoading = false,
                            isLoginSuccess = false,
                            authToken = null,
                            errorMessage = loginResponse.msg ?: "登录失败"
                        )
                    }
                },
                onFailure = { exception ->
                    // 网络请求失败
                    _loginState.value = currentState.copy(
                        isLoading = false,
                        isLoginSuccess = false,
                        authToken = null,
                        errorMessage = exception.message ?: "网络请求失败"
                    )
                }
            )
        }
    }
    // 清除保存的登录信息
    fun clearSavedLoginInfo() {
        PreferenceManager.clearLoginInfo()
        rememberMe.value = false
        autoLogin.value = false
        _loginState.value = LoginState()
        println("🔐 LoginViewModel: 已清除保存的登录信息")
    }

    // 获取认证token（在其他地方使用）
    fun getAuthToken(): String? {
        return _loginState.value.authToken
    }


}