package com.example.defenseapplication.login

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import bean.ForgotRequest
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.ForgetPasswordActivityBinding
import com.example.defenseapplication.utils.RetrofitNetwork
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.util.TextUtils
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.regex.Pattern

class ForgetPasswordActivity : AppCompatActivity() {
    private lateinit var binding: ForgetPasswordActivityBinding
    private var countDownTimer: CountDownTimer? = null
    private var isSendingCode = false

    companion object {
        private const val COUNTDOWN_DURATION = 60000L
        private const val COUNTDOWN_INTERVAL = 1000L
        private const val MIN_PASSWORD_LENGTH = 6
        private const val MAX_PASSWORD_LENGTH = 20
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ForgetPasswordActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topContainer)
            .init()
        val startColor = Color.parseColor("#CBEBFA")
        val endColor = Color.parseColor("#FFF2EF")
        setGradientBackground(binding.main, startColor, endColor)
        setupClickListeners()
    }

    private fun setupClickListeners() {
        binding.backIcon.setOnClickListener {
            finish()
        }

        binding.sendCodeBtn.setOnClickListener {
            if (!isSendingCode && countDownTimer == null) {
                val phoneNumber = binding.etPhoneNumber.text.toString().trim()
                if (isPhoneNumberValid(phoneNumber)) {
                    sendVerificationCode(phoneNumber)
                } else {
                    Toast.makeText(this, "请输入有效的11位手机号", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "请稍后再试", Toast.LENGTH_SHORT).show()
            }
        }

        binding.btnNext.setOnClickListener {
            performResetPassword()
        }
    }

    private fun isPhoneNumberValid(phone: String): Boolean {
        if (TextUtils.isEmpty(phone)) return false
        val pattern = Pattern.compile("^1[0-9]{10}$")
        return pattern.matcher(phone).matches()
    }

    private fun sendVerificationCode(phoneNumber: String) {
        isSendingCode = true
        binding.sendCodeBtn.isEnabled = false

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getCode(phoneNumber)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        Toast.makeText(this@ForgetPasswordActivity, "验证码已发送", Toast.LENGTH_SHORT).show()
                        startCountDown()
                    } else {
                        Toast.makeText(this@ForgetPasswordActivity, response.msg, Toast.LENGTH_SHORT).show()
                        binding.sendCodeBtn.isEnabled = true
                        isSendingCode = false
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ForgetPasswordActivity, R.string.network_error, Toast.LENGTH_SHORT).show()
                    binding.sendCodeBtn.isEnabled = true
                    isSendingCode = false
                }
            }
        }
    }

    /**
     * 开始验证码按钮倒计时
     */
    private fun startCountDown() {
        countDownTimer = object : CountDownTimer(COUNTDOWN_DURATION, COUNTDOWN_INTERVAL) {
            override fun onTick(millisUntilFinished: Long) {
                val secondsRemaining = (millisUntilFinished / 1000).toInt()
                binding.sendCodeBtn.text = "${secondsRemaining}秒后重试"
                binding.sendCodeBtn.isEnabled = false
            }

            override fun onFinish() {
                resetSendButton()
            }
        }.start()
    }

    /**
     * 重置发送按钮状态
     */
    private fun resetSendButton() {
        countDownTimer?.cancel()
        countDownTimer = null
        binding.sendCodeBtn.text = "发送验证码"
        binding.sendCodeBtn.isEnabled = true
    }

    /**
     * 执行重置密码请求
     */
    private fun performResetPassword() {
        val phoneNumber = binding.etPhoneNumber.text.toString().trim()
        val smsCode = binding.etSmsCode.text.toString().trim()
        val newPassword = binding.etPassword.text.toString().trim()
        val confirmPassword = binding.etInviteCode.text.toString().trim()

        if (!isPhoneNumberValid(phoneNumber)) {
            Toast.makeText(this, "手机号格式不正确", Toast.LENGTH_SHORT).show()
            return
        }

        if (TextUtils.isEmpty(smsCode)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show()
            return
        }

        if (TextUtils.isEmpty(newPassword) || TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (newPassword.length < MIN_PASSWORD_LENGTH || newPassword.length > MAX_PASSWORD_LENGTH) {
            Toast.makeText(this, "密码长度需为${MIN_PASSWORD_LENGTH}-${MAX_PASSWORD_LENGTH}位", Toast.LENGTH_SHORT).show()
            return
        }
        if (!newPassword.matches(Regex(".*[A-Za-z].*")) || !newPassword.matches(Regex(".*[0-9].*"))) {
            Toast.makeText(this, "密码需同时包含字母和数字", Toast.LENGTH_SHORT).show()
            return
        }
        if (newPassword != confirmPassword) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show()
            return
        }

        binding.btnNext.isEnabled = false
        binding.btnNext.text = "重置中..."

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val forgotRequest = ForgotRequest(
                    phonenumber = phoneNumber,
                    smsCode = smsCode,
                    password = newPassword
                )
                val response = RetrofitNetwork.getNetworkService().forgotPassword(forgotRequest)
                withContext(Dispatchers.Main) {
                    binding.btnNext.isEnabled = true
                    binding.btnNext.text = "确定"

                    if (response.code == 200) {
                        Toast.makeText(this@ForgetPasswordActivity, R.string.reset_success, Toast.LENGTH_SHORT).show()
                        finish()
                    } else {
                        Toast.makeText(this@ForgetPasswordActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    binding.btnNext.isEnabled = true
                    binding.btnNext.text = "确定"
                    Toast.makeText(this@ForgetPasswordActivity, 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
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        countDownTimer = null
    }
}