package com.narutohuo.xindazhou.auth.ui.register

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.ui.BaseActivity
import com.narutohuo.xindazhou.databinding.ActivityRegisterBinding
import com.narutohuo.xindazhou.socketio.SocketIOManager
import com.narutohuo.xindazhou.auth.ui.viewmodel.RegisterViewModel
import com.narutohuo.xindazhou.auth.ui.viewmodel.RegisterViewModelFactory
import com.narutohuo.xindazhou.auth.ui.viewmodel.RegisterState
import com.narutohuo.xindazhou.vehicle.ui.VehicleActivity
import kotlinx.coroutines.launch

/**
 * 注册 Activity
 * 
 * 多 Activity 架构：注册模块独立 Activity
 */
class RegisterActivity : BaseActivity<ActivityRegisterBinding>() {
    
    private lateinit var viewModel: RegisterViewModel
    private lateinit var etMobile: TextInputEditText
    private lateinit var etPassword: TextInputEditText
    private lateinit var etConfirmPassword: TextInputEditText
    private lateinit var btnRegister: MaterialButton
    private lateinit var btnBackToLogin: MaterialButton
    private lateinit var progressBar: View
    
    override fun getViewBinding(): ActivityRegisterBinding {
        return ActivityRegisterBinding.inflate(layoutInflater)
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化 ViewModel
        viewModel = ViewModelProvider(
            this,
            RegisterViewModelFactory(application)
        )[RegisterViewModel::class.java]
        
        initView()
        observeRegisterState()
    }
    
    override fun initView() {
        etMobile = binding.etMobile
        etPassword = binding.etPassword
        etConfirmPassword = binding.etConfirmPassword
        btnRegister = binding.btnRegister
        btnBackToLogin = binding.btnBackToLogin
        progressBar = binding.progressBar
        
        // 注册按钮
        btnRegister.setOnClickListener {
            val mobile = etMobile.text?.toString()?.trim() ?: ""
            val password = etPassword.text?.toString() ?: ""
            val confirmPassword = etConfirmPassword.text?.toString() ?: ""
            
            // 简单的前端验证（ViewModel 中也会验证，这里双重保护）
            if (password != confirmPassword) {
                Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            // 调用 ViewModel 方法（简单！）
            viewModel.register(mobile, password)
        }
        
        // 返回登录按钮
        btnBackToLogin.setOnClickListener {
            navigateToLogin()
        }
    }
    
    /**
     * 观察注册状态（MVVM 模式：Activity 只负责观察状态，更新 UI）
     */
    private fun observeRegisterState() {
        lifecycleScope.launch {
            viewModel.registerState.collect { state ->
                when (state) {
                    is RegisterState.Idle -> {
                        // 初始状态，什么都不做
                    }
                    is RegisterState.Loading -> {
                        // 显示加载状态
                        progressBar.visibility = View.VISIBLE
                        btnRegister.isEnabled = false
                    }
                    is RegisterState.Success -> {
                        // 注册成功
                        progressBar.visibility = View.GONE
                        btnRegister.isEnabled = true
                        Toast.makeText(this@RegisterActivity, state.message, Toast.LENGTH_SHORT).show()
                        // 注册成功后，确保 SocketIO 已连接
                        SocketIOManager.ensureConnected()
                        // 跳转到登录页
                        navigateToLogin()
                        // 重置状态
                        viewModel.resetState()
                    }
                    is RegisterState.Error -> {
                        // 注册失败
                        progressBar.visibility = View.GONE
                        btnRegister.isEnabled = true
                        Toast.makeText(this@RegisterActivity, state.message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
    
    // ==================== 导航方法 ====================
    
    private fun navigateToMain() {
        startActivity(Intent(this, VehicleActivity::class.java))
        finish()
    }
    
    private fun navigateToLogin() {
        startActivity(Intent(this, com.narutohuo.xindazhou.auth.ui.login.LoginActivity::class.java))
        finish()
    }
}

