package com.example.defenseapplication.personal

import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.defenseapplication.R
import com.example.defenseapplication.bean.UpdateUserInfo
import com.example.defenseapplication.bean.UserInfoBean
import com.example.defenseapplication.databinding.PersonalProfileActivityBinding
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.view.CustomDialogFragmentText
import com.example.defenseapplication.view.PhoneModifyDialogFragment
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
//个人资料
class PersonalProfileActivity : AppCompatActivity() {
    private lateinit var binding: PersonalProfileActivityBinding
    private var userInfo: UserInfoBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = PersonalProfileActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            userInfo = intent.getParcelableExtra("userInfo", UserInfoBean::class.java)
        }
        initView()
    }

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

        userInfo?.let { info ->
            Log.d("头像", "头像 URL = ${info.avatar}")
            val requestOptions = RequestOptions()
                .placeholder(R.drawable.img)   // 加载中显示
                .error(R.drawable.img)         // 失败时显示

            Glide.with(this)
                .load(info.avatar)             // 如果 avatar 为 null，Glide 会直接回调 error
                .apply(requestOptions)
                .circleCrop()
                .into(binding.ivAvatar)
            binding.tvNickname.text = info.nickName ?: getString(R.string.nickname_default)
            binding.tvPhone.text = info.phonenumber ?: ""
        }

        binding.itemNickname.setOnClickListener {
            showNicknameDialog()
        }

        binding.itemPhone.setOnClickListener {
            showPhoneDialog()
        }
    }

    private fun showNicknameDialog() {
        val currentNickname = binding.tvNickname.text.toString()
        val dialog = CustomDialogFragmentText()
            .setTitle(getString(R.string.set_name))
            .setMessage("")
            .setInputHint(getString(R.string.nickname_hint))
            .setInputText(currentNickname)
            .setShowInput(true)
            .setPositiveText(getString(R.string.confirm))
            .setNegativeText("")
            .setOnConfirmListener { newNickname ->
                if (newNickname.isNotBlank()) {
                    updateNickname(newNickname)
                }
            }
        dialog.show(supportFragmentManager, "nickname_dialog")
    }

    private fun updateNickname(newNickname: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val request = UpdateUserInfo(
                    userId = userInfo?.userId,
                    nickName = newNickname
                )
                val response = RetrofitNetwork.getNetworkService().updateUserInfo(request)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        binding.tvNickname.text = newNickname
                        userInfo = userInfo?.copy(nickName = newNickname)
                        Toast.makeText(this@PersonalProfileActivity, getString(R.string.operation_success), Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@PersonalProfileActivity, getString(R.string.operation_failed), Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@PersonalProfileActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun showPhoneDialog() {
        val dialog = PhoneModifyDialogFragment()
            .setTitle(getString(R.string.modify_phone))
            .setNegativeText(getString(R.string.cancel))
            .setPositiveText(getString(R.string.verify_and_bind))
            .setOnConfirmListener { phone, code ->
                updatePhone(phone, code)
            }
        dialog.show(supportFragmentManager, "phone_dialog")
    }

    private fun updatePhone(phone: String, code: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val request = UpdateUserInfo(
                    userId = userInfo?.userId,
                    phonenumber = phone,
                    smsCoode = code
                )
                val response = RetrofitNetwork.getNetworkService().updateUserInfo(request)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        binding.tvPhone.text = phone
                        userInfo = userInfo?.copy(phonenumber = phone)
                        Toast.makeText(this@PersonalProfileActivity, getString(R.string.operation_success), Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@PersonalProfileActivity, getString(R.string.operation_failed), Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@PersonalProfileActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}
