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.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import bean.RegisterRequest
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.RegisterActivityBinding
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 RegisterActivity : AppCompatActivity() {
    private lateinit var binding: RegisterActivityBinding
    private var isLoading = false
    private var countDownTimer: CountDownTimer? = null
    private var isSendingCode = false

    companion object {
        private const val COUNTDOWN_DURATION = 60000L
        private const val COUNTDOWN_INTERVAL = 1000L
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = RegisterActivityBinding.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.topContainer)
            .init()

        setupListeners()
    }

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

        binding.sendCodeBtn.setOnClickListener {
            if (!isSendingCode && countDownTimer == null) {
                val phone = binding.etPhoneNumber.text.toString().trim()
                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
                }
                sendVerificationCode(phone)
            }
        }

        binding.btnNext.setOnClickListener {
            if (!isLoading) {
                performRegistration()
            }
        }
    }

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

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getCode(userName)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        Toast.makeText(this@RegisterActivity, "验证码已发送", Toast.LENGTH_SHORT).show()
                        startCountDown()
                    } else {
                        Toast.makeText(this@RegisterActivity, response.msg, Toast.LENGTH_SHORT).show()
                        binding.sendCodeBtn.isEnabled = true
                        isSendingCode = false
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@RegisterActivity, 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 = getString(R.string.send_code)
        binding.sendCodeBtn.isEnabled = true
        isSendingCode = false
    }

    private fun performRegistration() {
        val phone = binding.etPhoneNumber.text.toString().trim()
        val smsCode = binding.etSmsCode.text.toString().trim()
        val idCard = binding.etIdNumber.text.toString().trim()
        val password = binding.etPassword.text.toString().trim()
        val inviteCode = binding.etInviteCode.text.toString().trim()

        if (phone.isEmpty()) {
            Toast.makeText(this, R.string.enter_phone_number, Toast.LENGTH_SHORT).show()
            return
        }
        if (phone.length != 11) {
            Toast.makeText(this, R.string.phone_format_invalid, Toast.LENGTH_SHORT).show()
            return
        }
        if (smsCode.isEmpty()) {
            Toast.makeText(this, R.string.enter_verification_code_pls, Toast.LENGTH_SHORT).show()
            return
        }
        if (idCard.isEmpty()) {
            Toast.makeText(this, R.string.enter_id_number, Toast.LENGTH_SHORT).show()
            return
        }
        if (idCard.length != 18) {
            Toast.makeText(this, R.string.hint_input_correct_id_card, Toast.LENGTH_SHORT).show()
            return
        }
        if (password.isEmpty()) {
            Toast.makeText(this, R.string.password_hint, Toast.LENGTH_SHORT).show()
            return
        }
        if (password.length < 6 || password.length > 20) {
            Toast.makeText(this, R.string.password_requirement, Toast.LENGTH_SHORT).show()
            return
        }

        isLoading = true
        binding.btnNext.isEnabled = false
        binding.btnNext.text = getString(R.string.registering)

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val registerRequest = RegisterRequest(
                    grantType = "password",
                    smsCode = smsCode,
                    username = phone,
                    password = password,
                    idCard = idCard,
                    inviteCode = if (inviteCode.isEmpty()) null else inviteCode,
                    faceAddr = "https://tiebapic.baidu.com/forum/pic/item/2924ab18972bd407021da3e33d899e510eb309d1.jpg?tbpicau=2026-04-22-05_44105254d24a81214177d11b72513421"
                )
                val response = RetrofitNetwork.getNetworkService().register(registerRequest)
                withContext(Dispatchers.Main) {
                    isLoading = false
                    binding.btnNext.isEnabled = true
                    binding.btnNext.text = getString(R.string.next_step)

                    if (response.code == 200) {
                        Toast.makeText(this@RegisterActivity, R.string.register_success, Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@RegisterActivity, LoginActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        startActivity(intent)
                        finish()
                    } else {
                        Toast.makeText(this@RegisterActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    isLoading = false
                    binding.btnNext.isEnabled = true
                    binding.btnNext.text = getString(R.string.next_step)
                    Toast.makeText(this@RegisterActivity, 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
    }
}