package com.example.defenseapplication.login

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import bean.LoginRequest
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.ActivityLoginBinding
import com.example.defenseapplication.home.HomeActivity
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.utils.UserinfoUtil
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding
    private var currentLoginMode = LoginMode.SMS

    enum class LoginMode { SMS, PASSWORD }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        if (UserinfoUtil.getUserInfo() != null) {
            val intent = Intent(this, HomeActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            startActivity(intent)
            finish()
            return
        }
        
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val startColor = Color.parseColor("#CBEBFA")
        val endColor = Color.parseColor("#FFF2EF")
        setGradientBackground(binding.main, startColor, endColor)

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.logoFrame)
            .init()

        setupTabListeners()
        setupClickListeners()
        switchToSmsMode()
    }

    private fun setupTabListeners() {
        binding.tvSmsLogin.setOnClickListener {
            if (currentLoginMode != LoginMode.SMS) {
                currentLoginMode = LoginMode.SMS
                switchToSmsMode()
            }
        }
        binding.tvPwdLogin.setOnClickListener {
            if (currentLoginMode != LoginMode.PASSWORD) {
                currentLoginMode = LoginMode.PASSWORD
                switchToPasswordMode()
            }
        }
    }

    private fun switchToSmsMode() {
        binding.tvSmsLogin.setTextColor(getColor(R.color.black))
        binding.tvPwdLogin.setTextColor(getColor(R.color.gray))

        binding.smsRowLayout.visibility = View.VISIBLE
        binding.passwordRowLayout.visibility = View.GONE   // 隐藏密码行容器

        binding.registerText.visibility = View.VISIBLE
        binding.forgetText.visibility = View.GONE
        updateRegisterTextConstraints(center = false)

        //需要正确的方法名和参数
        updateLoginButtonTopConstraint(R.id.smsRowLayout)
    }

    private fun switchToPasswordMode() {
        binding.tvPwdLogin.setTextColor(getColor(R.color.black))
        binding.tvSmsLogin.setTextColor(getColor(R.color.gray))

        binding.smsRowLayout.visibility = View.GONE
        //正确的属性访问
        binding.passwordRowLayout.visibility = View.VISIBLE  // 显示密码行容器

        binding.registerText.visibility = View.VISIBLE
        binding.forgetText.visibility = View.VISIBLE
        updateRegisterTextConstraints(center = false)

        updateLoginButtonTopConstraint(R.id.passwordRowLayout)
    }

    // 动态修改登录按钮的顶部约束
    private fun updateLoginButtonTopConstraint(topTargetId: Int) {
        val params = binding.loginBtn.layoutParams as ConstraintLayout.LayoutParams
        params.topToBottom = topTargetId
        params.topMargin = 32
        binding.loginBtn.layoutParams = params
    }

    // 动态修改立即注册的约束（居中/左对齐）
    private fun updateRegisterTextConstraints(center: Boolean) {
        val params = binding.registerText.layoutParams as ConstraintLayout.LayoutParams
        if (center) {
            // 短信模式：居中显示
            params.startToStart = ConstraintSet.PARENT_ID
            params.endToEnd = ConstraintSet.PARENT_ID
        } else {
            // 密码模式：左对齐登录按钮
            params.startToStart = binding.loginBtn.id
            params.endToEnd = ConstraintSet.UNSET
        }
        params.topToBottom  = binding.loginBtn.id
        params.topMargin = 20
        binding.registerText.layoutParams = params
    }

    private fun setupClickListeners() {
        binding.loginBtn.setOnClickListener {
            val phone = binding.etPhone.text.toString()
            if (phone.isEmpty()) {
                Toast.makeText(this, R.string.enter_phone_number, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (phone.length != 11) {
                Toast.makeText(this, R.string.phone_format_invalid, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            when (currentLoginMode) {
                LoginMode.SMS -> {
                    val code = binding.etSmsCode.text.toString()
                    if (code.isEmpty()) {
                        Toast.makeText(this, R.string.enter_verification_code_pls, Toast.LENGTH_SHORT).show()
                    } else {
                        smsLogin(phone, code)
                    }
                }
                LoginMode.PASSWORD -> {
                    val pwd = binding.etPassword.text.toString()
                    if (pwd.isEmpty()) {
                        Toast.makeText(this, R.string.password_hint, Toast.LENGTH_SHORT).show()
                    } else {
                        passwordLogin(phone, pwd)
                    }
                }
            }
        }

        binding.sendCodeBtn.setOnClickListener {
            val phone = binding.etPhone.text.toString()
            if (phone.isEmpty()) {
                Toast.makeText(this, R.string.phone_hint, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (phone.length != 11) {
                Toast.makeText(this, R.string.phone_format_invalid, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            sendVerificationCode(phone)
        }

        binding.registerText.setOnClickListener {
            val intent= Intent(this, RegisterActivity::class.java)
            startActivity(intent)
            Toast.makeText(this, R.string.redirect_register_page, Toast.LENGTH_SHORT).show()
        }

        binding.forgetText.setOnClickListener {
            val intent= Intent(this, ForgetPasswordActivity::class.java)
            startActivity(intent)
            Toast.makeText(this, R.string.forgot_password_page, Toast.LENGTH_SHORT).show()
        }
    }

    private fun startCountDown() {
        binding.sendCodeBtn.isEnabled = false
        object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                binding.sendCodeBtn.text = getString(R.string.countdown_retry, millisUntilFinished / 1000)
            }
            override fun onFinish() {
                binding.sendCodeBtn.text = getString(R.string.send_code)
                binding.sendCodeBtn.isEnabled = true
            }
        }.start()
    }

    private fun sendVerificationCode(phone: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getCode(phone)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        Toast.makeText(this@LoginActivity, getString(R.string.code_sent_to, phone), Toast.LENGTH_SHORT).show()
                        startCountDown()
                    } else {
                        Toast.makeText(this@LoginActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@LoginActivity, R.string.network_error, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun smsLogin(phone: String, smsCode: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val loginRequest = LoginRequest(
                    grantType = "sms",
                    username = phone,
                    phonenumber = phone,
                    smsCode = smsCode
                )
                android.util.Log.d("LoginActivity", "短信登录请求: $loginRequest")
                val response = RetrofitNetwork.getNetworkService().login(loginRequest)
                android.util.Log.d("LoginActivity", "短信登录响应: code=${response.code}, msg=${response.msg}")
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        UserinfoUtil.saveUserInfo(response.data)
                        Toast.makeText(this@LoginActivity, R.string.sms_login_success_title, Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@LoginActivity, HomeActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        startActivity(intent)
                        finish()
                    } else {
                        Toast.makeText(this@LoginActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                android.util.Log.e("LoginActivity", "短信登录异常", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@LoginActivity, R.string.network_error, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun passwordLogin(phone: String, password: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val loginRequest = LoginRequest(
                    grantType = "password",
                    username = phone,
                    phonenumber = phone,
                    password = password
                )
                android.util.Log.d("LoginActivity", "密码登录请求: $loginRequest")
                val response = RetrofitNetwork.getNetworkService().login(loginRequest)
                android.util.Log.d("LoginActivity", "密码登录响应: code=${response.code}, msg=${response.msg}")
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        UserinfoUtil.saveUserInfo(response.data)
                        Toast.makeText(this@LoginActivity, R.string.password_login_success_title, Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@LoginActivity, HomeActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        startActivity(intent)
                        finish()
                    } else {
                        Toast.makeText(this@LoginActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                android.util.Log.e("LoginActivity", "密码登录异常", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@LoginActivity, R.string.network_error, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun setGradientBackground(
        view: android.view.View,
        startColor: Int,
        endColor: Int,
        orientation: GradientDrawable.Orientation = GradientDrawable.Orientation.TL_BR
    ) {
        val gradientDrawable = GradientDrawable(orientation, intArrayOf(startColor, endColor))
        gradientDrawable.gradientType = GradientDrawable.LINEAR_GRADIENT
        view.background = gradientDrawable
    }
}