// ui/login/LoginSmsViewModel.kt
package com.example.initiateaphonecallapp.ui.LoginSms

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.repository.AuthRepository
import com.example.initiateaphonecallapp.manager.PreferenceManager
import com.example.initiateaphonecallapp.manager.TokenManager
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

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

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

    private var countdownJob: Job? = null

    fun onPhoneChange(phone: String) {
        _loginState.value = _loginState.value.copy(
            phone = phone,
            errorMessage = ""
        )
    }

    fun onCodeChange(code: String) {
        _loginState.value = _loginState.value.copy(
            code = code,
            errorMessage = ""
        )
    }

    // 获取验证码
    fun getCode() {
        val currentState = _loginState.value

        if (currentState.phone.isEmpty()) {
            _loginState.value = currentState.copy(
                errorMessage = "请输入手机号"
            )
            return
        }

        if (!isValidPhone(currentState.phone)) {
            _loginState.value = currentState.copy(
                errorMessage = "请输入正确的手机号"
            )
            return
        }

        if (currentState.countdown > 0) {
            return // 正在倒计时，不能重复获取
        }

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

        viewModelScope.launch {
            val result = authRepository.getCode(currentState.phone)

            result.fold(
                onSuccess = {
                    _loginState.value = currentState.copy(
                        isGetCodeLoading = false,
                        errorMessage = ""
                    )
                    startCountdown()
                },
                onFailure = { exception ->
                    _loginState.value = currentState.copy(
                        isGetCodeLoading = false,
                        errorMessage = exception.message ?: "获取验证码失败"
                    )
                }
            )
        }
    }

    // 验证码登录
    fun loginSms() {
        val currentState = _loginState.value

        if (currentState.phone.isEmpty() || currentState.code.isEmpty()) {
            _loginState.value = currentState.copy(
                errorMessage = "请填写手机号和验证码"
            )
            return
        }

        if (!isValidPhone(currentState.phone)) {
            _loginState.value = currentState.copy(
                errorMessage = "请输入正确的手机号"
            )
            return
        }

        if (currentState.code.length != 6) {
            _loginState.value = currentState.copy(
                errorMessage = "验证码必须是6位数字"
            )
            return
        }

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

        viewModelScope.launch {
            val result = authRepository.loginSms(
                phone = currentState.phone,
                code = currentState.code
            )

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

                        // 保存登录信息（只保存token，不保存密码）
                        loginResponse.token?.let { token ->
                            PreferenceManager.saveLoginInfo(
                                username = currentState.phone, // 使用手机号作为用户名
                                password = "", // 验证码登录不需要密码
                                token = token,
                                rememberMe = true, // 验证码登录默认记住
                                autoLogin = false  // 验证码登录默认不自动登录
                            )
                        }

                        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 ?: "网络请求失败"
                    )
                }
            )
        }
    }

    // 开始倒计时
    private fun startCountdown() {
        countdownJob?.cancel()
        countdownJob = viewModelScope.launch {
            var count = 60
            while (count > 0) {
                _loginState.value = _loginState.value.copy(countdown = count)
                delay(1000)
                count--
            }
            _loginState.value = _loginState.value.copy(countdown = 0)
        }
    }

    // 验证手机号格式
    private fun isValidPhone(phone: String): Boolean {
        return phone.matches(Regex("^1[3-9]\\d{9}$"))
    }

    // 清理资源
    override fun onCleared() {
        super.onCleared()
        countdownJob?.cancel()
    }

    // 清除状态
    fun clearState() {
        countdownJob?.cancel()
        _loginState.value = LoginSmsState()
    }
}