package com.safecheckin.app.ui.screens.auth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.safecheckin.app.data.api.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

data class AuthUiState(
    val serverUrl: String = "http://localhost:8000",
    val email: String = "",
    val password: String = "",
    val verificationCode: String = "",
    val newPassword: String = "",        // 重置密码用
    val confirmPassword: String = "",      // 确认新密码
    val isLoading: Boolean = false,
    val isLoggedIn: Boolean = false,
    val isRegistered: Boolean = false,
    val isCodeSent: Boolean = false,
    val isResetCodeSent: Boolean = false, // 忘记密码验证码
    val errorMessage: String? = null,
    val successMessage: String? = null,
    val userId: Int = -1
)

class AuthViewModel(
    private val apiClient: ApiClient
) : ViewModel() {

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

    init {
        // 加载保存的服务器地址和登录状态
        viewModelScope.launch {
            apiClient.baseUrl.collect { url ->
                _uiState.update { it.copy(serverUrl = url) }
            }
        }
        viewModelScope.launch {
            apiClient.isLoggedIn.collect { isLoggedIn ->
                _uiState.update { it.copy(isLoggedIn = isLoggedIn) }
            }
        }
        viewModelScope.launch {
            apiClient.userId.collect { userId ->
                _uiState.update { it.copy(userId = userId) }
            }
        }
    }

    fun updateServerUrl(url: String) {
        _uiState.update { it.copy(serverUrl = url, errorMessage = null, successMessage = null) }
        viewModelScope.launch {
            apiClient.setBaseUrl(url)
        }
    }

    fun updateEmail(email: String) {
        _uiState.update { it.copy(email = email, errorMessage = null, successMessage = null) }
    }

    fun updatePassword(password: String) {
        _uiState.update { it.copy(password = password, errorMessage = null) }
    }

    fun updateVerificationCode(code: String) {
        _uiState.update { it.copy(verificationCode = code, errorMessage = null) }
    }

    fun updateNewPassword(password: String) {
        _uiState.update { it.copy(newPassword = password, errorMessage = null) }
    }

    fun updateConfirmPassword(password: String) {
        _uiState.update { it.copy(confirmPassword = password, errorMessage = null) }
    }

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

    fun login() {
        val state = _uiState.value
        if (state.email.isBlank() || state.password.isBlank()) {
            _uiState.update { it.copy(errorMessage = "请输入邮箱和密码") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val api = apiClient.createApiSync(state.serverUrl)
                val response = api.login(LoginRequest(state.email, state.password))
                
                if (response.isSuccessful) {
                    response.body()?.let { body ->
                        apiClient.saveLoginState(body.userId, body.email)
                        _uiState.update { 
                            it.copy(
                                isLoading = false, 
                                isLoggedIn = true,
                                userId = body.userId
                            )
                        }
                    }
                } else {
                    val errorBody = response.errorBody()?.string() ?: "未知错误"
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            errorMessage = "登录失败: $errorBody"
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(isLoading = false, errorMessage = "网络错误: ${e.message}")
                }
            }
        }
    }

    fun sendVerificationCode() {
        val state = _uiState.value
        if (state.email.isBlank() || state.password.isBlank()) {
            _uiState.update { it.copy(errorMessage = "请输入邮箱和密码") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val api = apiClient.createApiSync(state.serverUrl)
                val response = api.register(RegisterRequest(state.email, state.password))
                
                if (response.isSuccessful) {
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            isCodeSent = true,
                            successMessage = "验证码已发送至 ${state.email}"
                        )
                    }
                } else {
                    val errorBody = response.errorBody()?.string() ?: "未知错误"
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            errorMessage = "发送失败: $errorBody"
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(isLoading = false, errorMessage = "网络错误: ${e.message}")
                }
            }
        }
    }

    fun verifyAndRegister() {
        val state = _uiState.value
        if (state.verificationCode.isBlank()) {
            _uiState.update { it.copy(errorMessage = "请输入验证码") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val api = apiClient.createApiSync(state.serverUrl)
                val response = api.verifyCode(VerifyCodeRequest(state.email, state.verificationCode))
                
                if (response.isSuccessful) {
                    response.body()?.let { body ->
                        apiClient.saveLoginState(body.userId, body.email)
                        _uiState.update { 
                            it.copy(
                                isLoading = false, 
                                isRegistered = true,
                                userId = body.userId
                            )
                        }
                    }
                } else {
                    val errorBody = response.errorBody()?.string() ?: "未知错误"
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            errorMessage = "验证失败: $errorBody"
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(isLoading = false, errorMessage = "网络错误: ${e.message}")
                }
            }
        }
    }

    /**
     * 发送忘记密码验证码
     */
    fun sendResetCode() {
        val state = _uiState.value
        if (state.email.isBlank()) {
            _uiState.update { it.copy(errorMessage = "请输入邮箱地址") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null, successMessage = null) }
            try {
                val api = apiClient.createApiSync(state.serverUrl)
                val response = api.forgotPassword(ForgotPasswordRequest(state.email))
                
                if (response.isSuccessful) {
                    response.body()?.let { body ->
                        _uiState.update { 
                            it.copy(
                                isLoading = false, 
                                isResetCodeSent = true,
                                successMessage = body.message
                            )
                        }
                    }
                } else {
                    val errorBody = response.errorBody()?.string() ?: "未知错误"
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            errorMessage = errorBody
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(isLoading = false, errorMessage = "网络错误: ${e.message}")
                }
            }
        }
    }

    /**
     * 重置密码
     */
    fun resetPassword() {
        val state = _uiState.value
        
        if (state.verificationCode.isBlank()) {
            _uiState.update { it.copy(errorMessage = "请输入验证码") }
            return
        }
        if (state.newPassword.isBlank()) {
            _uiState.update { it.copy(errorMessage = "请输入新密码") }
            return
        }
        if (state.newPassword.length < 6) {
            _uiState.update { it.copy(errorMessage = "密码长度至少6位") }
            return
        }
        if (state.newPassword != state.confirmPassword) {
            _uiState.update { it.copy(errorMessage = "两次密码输入不一致") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val api = apiClient.createApiSync(state.serverUrl)
                val response = api.resetPassword(
                    ResetPasswordRequest(
                        email = state.email,
                        code = state.verificationCode,
                        newPassword = state.newPassword
                    )
                )
                
                if (response.isSuccessful) {
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            successMessage = "密码重置成功，请使用新密码登录"
                        )
                    }
                } else {
                    val errorBody = response.errorBody()?.string() ?: "未知错误"
                    _uiState.update { 
                        it.copy(
                            isLoading = false, 
                            errorMessage = "重置失败: $errorBody"
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(isLoading = false, errorMessage = "网络错误: ${e.message}")
                }
            }
        }
    }

    /**
     * 退出登录 - 清理所有登录状态
     */
    fun logout() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            try {
                // 清理登录状态
                apiClient.clearLoginState()
                
                // 重置UI状态
                _uiState.update { 
                    AuthUiState(serverUrl = it.serverUrl)
                }
            } catch (e: Exception) {
                // 即使出错也要清理本地状态
                _uiState.update { 
                    AuthUiState(serverUrl = it.serverUrl)
                }
            }
        }
    }

    /**
     * 重置到登录状态（用于忘记密码流程完成后）
     */
    fun resetToLogin() {
        _uiState.update { 
            AuthUiState(serverUrl = it.serverUrl)
        }
    }

    class Factory(private val apiClient: ApiClient) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
            return AuthViewModel(apiClient) as T
        }
    }
}
