package com.example.defenseapplication.personal

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.RetrievePasswordActivityBinding
import com.example.defenseapplication.utils.RetrofitNetwork
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//找回密码页面
class RetrievePasswordActivity : AppCompatActivity() {

    private lateinit var binding: RetrievePasswordActivityBinding
    private var countDownTimer: CountDownTimer? = null
    private var isCountingDown = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = RetrievePasswordActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

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

        initListener()
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.btnGetCode.setOnClickListener {
            val phoneNumber = binding.etPhoneNumber.text.toString()

            if (phoneNumber.isEmpty()) {
                Toast.makeText(this, getString(R.string.enter_phone_number), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (phoneNumber.length != 11) {
                Toast.makeText(this, getString(R.string.phone_format_invalid), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            binding.btnGetCode.isEnabled = false

            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val response = RetrofitNetwork.getNetworkService().getCode(phoneNumber)
                    withContext(Dispatchers.Main) {
                        if (response.code == 200) {
                            startCountdown()
                            Toast.makeText(this@RetrievePasswordActivity, String.format(getString(R.string.code_sent_to), phoneNumber), Toast.LENGTH_SHORT).show()
                        } else {
                            binding.btnGetCode.isEnabled = true
                            Toast.makeText(this@RetrievePasswordActivity, response.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        binding.btnGetCode.isEnabled = true
                        Toast.makeText(this@RetrievePasswordActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        binding.btnConfirmReset.setOnClickListener {
            val phoneNumber = binding.etPhoneNumber.text.toString()
            val verificationCode = binding.etVerificationCode.text.toString()
            val newPassword = binding.etNewPassword.text.toString()
            val confirmPassword = binding.etConfirmPassword.text.toString()

            if (phoneNumber.isEmpty()) {
                Toast.makeText(this, getString(R.string.enter_phone_number), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (phoneNumber.length != 11) {
                Toast.makeText(this, getString(R.string.phone_format_invalid), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (verificationCode.isEmpty()) {
                Toast.makeText(this, getString(R.string.enter_verification_code_pls), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (verificationCode.length != 6) {
                Toast.makeText(this, getString(R.string.verification_code_error), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (newPassword.isEmpty()) {
                Toast.makeText(this, getString(R.string.password_cannot_empty), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (newPassword.length < 6 || newPassword.length > 20) {
                Toast.makeText(this, getString(R.string.password_requirement), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (confirmPassword.isEmpty()) {
                Toast.makeText(this, getString(R.string.enter_password_again), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (newPassword != confirmPassword) {
                Toast.makeText(this, getString(R.string.password_mismatch), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            binding.btnConfirmReset.isEnabled = false

            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val forgotRequest = ForgotRequest(
                        phonenumber = phoneNumber,
                        smsCode = verificationCode,
                        password = newPassword
                    )
                    val response = RetrofitNetwork.getNetworkService().retrievePassword(forgotRequest)
                    withContext(Dispatchers.Main) {
                        binding.btnConfirmReset.isEnabled = true
                        if (response.code == 200) {
                            Toast.makeText(this@RetrievePasswordActivity, getString(R.string.reset_success), Toast.LENGTH_SHORT).show()
                            finish()
                        } else {
                            Toast.makeText(this@RetrievePasswordActivity, response.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        binding.btnConfirmReset.isEnabled = true
                        Toast.makeText(this@RetrievePasswordActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun startCountdown() {
        isCountingDown = true
        binding.btnGetCode.isEnabled = false

        countDownTimer = object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val seconds = millisUntilFinished / 1000
                binding.btnGetCode.text = String.format(getString(R.string.countdown_retry), seconds)
            }

            override fun onFinish() {
                isCountingDown = false
                binding.btnGetCode.isEnabled = true
                binding.btnGetCode.text = getString(R.string.get_verification_code)
            }
        }.start()
    }

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