package com.narutohuo.xindazhou.auth.ui.login

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.narutohuo.xindazhou.R
import com.narutohuo.xindazhou.common.dialog.ServerConfigDialog
import com.narutohuo.xindazhou.common.ui.BaseActivity
import com.narutohuo.xindazhou.databinding.ActivityLoginBinding
import com.narutohuo.xindazhou.socketio.SocketIOManager
import com.narutohuo.xindazhou.auth.ui.viewmodel.LoginViewModel
import com.narutohuo.xindazhou.auth.ui.viewmodel.LoginViewModelFactory
import com.narutohuo.xindazhou.auth.ui.viewmodel.LoginState
import com.narutohuo.xindazhou.vehicle.ui.VehicleActivity
import kotlinx.coroutines.launch

/**
 * 登录 Activity
 * 
 * 多 Activity 架构：登录模块独立 Activity
 */
class LoginActivity : BaseActivity<ActivityLoginBinding>() {
    
    private lateinit var viewModel: LoginViewModel
    private lateinit var etMobile: TextInputEditText
    private lateinit var etPassword: TextInputEditText
    private lateinit var btnLogin: MaterialButton
    private lateinit var btnRegister: MaterialButton
    private lateinit var progressBar: View
    private var ivServerConfig: View? = null
    
    override fun getViewBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化 ViewModel
        viewModel = ViewModelProvider(
            this,
            LoginViewModelFactory(application)
        )[LoginViewModel::class.java]
        
        initView()
        observeLoginState()
    }
    
    override fun initView() {
        etMobile = binding.etMobile
        etPassword = binding.etPassword
        btnLogin = binding.btnLogin
        btnRegister = binding.btnRegister
        progressBar = binding.progressBar
        ivServerConfig = binding.ivServerConfig
        
        // 【测试功能】服务器配置按钮
        ivServerConfig?.setOnClickListener {
            val dialog = ServerConfigDialog()
            dialog.show(supportFragmentManager, "ServerConfigDialog")
        }
        
        // 登录按钮
        btnLogin.setOnClickListener {
            val mobile = etMobile.text?.toString()?.trim() ?: ""
            val password = etPassword.text?.toString() ?: ""
            
            // 调用 ViewModel 方法（简单！）
            viewModel.login(mobile, password)
        }
        
        // 注册按钮
        btnRegister.setOnClickListener {
            navigateToRegister()
        }
    }
    
    /**
     * 观察登录状态（MVVM 模式：Activity 只负责观察状态，更新 UI）
     */
    private fun observeLoginState() {
        lifecycleScope.launch {
            viewModel.loginState.collect { state ->
                when (state) {
                    is LoginState.Idle -> {
                        // 初始状态，什么都不做
                    }
                    is LoginState.Loading -> {
                        // 显示加载状态
                        progressBar.visibility = View.VISIBLE
                        btnLogin.isEnabled = false
                    }
                    is LoginState.Success -> {
                        // 登录成功
                        progressBar.visibility = View.GONE
                        btnLogin.isEnabled = true
                        Toast.makeText(this@LoginActivity, state.message, Toast.LENGTH_SHORT).show()
                        // 登录成功后，确保 SocketIO 已连接
                        SocketIOManager.ensureConnected()
                        // 跳转到主界面
                        navigateToMain()
                        // 重置状态
                        viewModel.resetState()
                    }
                    is LoginState.Error -> {
                        // 登录失败
                        progressBar.visibility = View.GONE
                        btnLogin.isEnabled = true
                        Toast.makeText(this@LoginActivity, state.message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
    
    // ==================== 导航方法 ====================
    
    private fun navigateToMain() {
        startActivity(Intent(this, VehicleActivity::class.java))
        finish()
    }
    
    private fun navigateToRegister() {
        startActivity(Intent(this, com.narutohuo.xindazhou.auth.ui.register.RegisterActivity::class.java))
    }
}

