package com.example.defenseapplication.home

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.UserInfoBean
import com.example.defenseapplication.databinding.PersonalFragmentBinding
import com.example.defenseapplication.liveVideo.LinkedUserActivity
import com.example.defenseapplication.personal.FaceManagementActivity
import com.example.defenseapplication.personal.PasswordManagementActivity
import com.example.defenseapplication.personal.PersonalProfileActivity
import com.example.defenseapplication.utils.AppLanguage
import com.example.defenseapplication.utils.LanguageUtil
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.utils.UserinfoUtil
import com.example.defenseapplication.utils.ActivityManager
import com.example.defenseapplication.view.FamilySwitchDialog
import com.example.defenseapplication.view.LanguageDialog
import com.example.defenseapplication.home.HomeActivity
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
//我的碎片
class PersonalFragment : Fragment() {
    // ViewBinding
    private var _binding: PersonalFragmentBinding? = null
    private val binding get() = _binding!!
    override fun onResume() {
        super.onResume()
        fetchUserInfo()
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = PersonalFragmentBinding.inflate(inflater, container, false)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.headerLayout)
            .init()
        Glide.with(this)
            .load(R.drawable.img)
            .circleCrop()
            .into(binding.ivAvatar)
        binding.headerLayout.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val response = RetrofitNetwork.getNetworkService().getUserInfo()
                    withContext(Dispatchers.Main) {
                        if (response.code == 200 && response.data != null) {
                            val intent = Intent(requireContext(), PersonalProfileActivity::class.java)
                            intent.putExtra("userInfo", response.data)
                            startActivity(intent)
                        } else {
                            val intent = Intent(requireContext(), PersonalProfileActivity::class.java)
                            startActivity(intent)
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    val intent = Intent(requireContext(), PersonalProfileActivity::class.java)
                    startActivity(intent)
                }
            }
        }
        // 更新当前语言显示
        updateCurrentLanguageDisplay()
        // 语言设置点击事件
        binding.itemLanguage.setOnClickListener {
            showLanguageDialog()
        }
        // 切换家庭点击事件
        binding.itemSwitchFamily.setOnClickListener {
            showFamilySwitchDialog()
        }
        //用户管理点击事件跳转关联用户页面
        binding.itemUserManage.setOnClickListener {
            val intent = Intent(requireContext(), LinkedUserActivity::class.java)
            intent.putExtra(LinkedUserActivity.EXTRA_MODE, LinkedUserActivity.MODE_PERSONAL)
            startActivity(intent)
        }
        // 密码管理点击事件
        binding.itemPwdManage.setOnClickListener {
            val intent= Intent(requireContext(), PasswordManagementActivity::class.java)
            startActivity(intent)
        }
        //人脸管理点击事件跳转人脸管理页面
        binding.itemFaceManage.setOnClickListener {
            val intent= Intent(requireContext(), FaceManagementActivity::class.java)
            startActivity(intent)
        }
        // 退出登录点击事件
        binding.btnLogout.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val response = RetrofitNetwork.getNetworkService().logout()
                    withContext(Dispatchers.Main) {
                        if (response.code == 200) {
                            UserinfoUtil.clearUserInfo()
                            val intent = Intent(requireContext(), com.example.defenseapplication.login.LoginActivity::class.java)
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                            startActivity(intent)
                            requireActivity().finish()
                        } else {
                            Toast.makeText(requireContext(), getString(R.string.logout_fail), Toast.LENGTH_SHORT).show()
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    withContext(Dispatchers.Main) {
                        Toast.makeText(requireContext(), getString(R.string.logout_fail), Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
        fetchCurrentFamily()
        return binding.root
    }

    private fun fetchCurrentFamily() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getFamilyList()
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        val userInfo = UserinfoUtil.getUserInfo()
                        val currentFamily = response.data.find {
                            it.role == userInfo?.role && it.role != "member"
                        } ?: response.data.firstOrNull()
                        currentFamily?.let {
                            val isAdmin = it.role == "appadmin"
                            if (isAdmin) {
                                binding.tvCurrentFamily.text = getString(R.string.my_family)
                            } else {
                                binding.tvCurrentFamily.text = "${it.parentName}${getString(R.string.family_with_normal)}"
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    /**
     * 更新当前语言显示
     */
    private fun updateCurrentLanguageDisplay() {
        binding.tvCurrentLanguage.text = LanguageUtil.currentLanguage.let {
            if (it == AppLanguage.SIMPLIFIED_CHINESE) "中文" else "English"
        }
    }

    /**
     * 显示语言选择对话框
     */
    private fun showLanguageDialog() {
        val dialog = LanguageDialog(requireContext()) { appLanguage ->
            LanguageUtil.switchLanguage(requireContext(), appLanguage)
            // 关闭所有 Activity，重启到首页
            ActivityManager.finishAllActivities()
            val intent = Intent(requireContext(), HomeActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            startActivity(intent)
            requireActivity().finish()
        }
        dialog.show()
    }

    /**
     * 显示家庭切换对话框
     */
    private fun showFamilySwitchDialog() {
        val dialog = FamilySwitchDialog(requireContext()) { familyName ->
            updateFamilyDisplay(familyName)
        }
        dialog.show()
    }

    private fun updateFamilyDisplay(familyName: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getFamilyList()
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        val family = response.data.find { it.parentName == familyName }
                        family?.let {
                            val isAdmin = it.role == "appadmin"
                            if (isAdmin) {
                                binding.tvCurrentFamily.text = getString(R.string.my_family)
                            } else {
                                binding.tvCurrentFamily.text = "${it.parentName}${getString(R.string.family_with_normal)}"
                            }
                        } ?: run {
                            binding.tvCurrentFamily.text = familyName
                        }
                    } else {
                        binding.tvCurrentFamily.text = familyName
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                binding.tvCurrentFamily.text = familyName
            }
        }
    }



    private fun fetchUserInfo() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getUserInfo()
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        updateUserUI(response.data)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun updateUserUI(userInfo: UserInfoBean) {
        userInfo.nickName?.let {
            binding.tvNickname.text = it
        }
        userInfo.phonenumber?.let {
            binding.tvPhone.text = it
        }
        userInfo.avatar?.let {
            val requestOptions = RequestOptions()
                .placeholder(R.drawable.img)   // 加载中显示
                .error(R.drawable.img)         // 失败时显示

            Glide.with(this)
                .load(it)             // 如果 avatar 为 null，Glide 会直接回调 error
                .apply(requestOptions)
                .circleCrop()
                .into(binding.ivAvatar)
        }
        userInfo.role?.let {
            binding.tvRoleTag.text = if (it == "appadmin") {
                getString(R.string.admin)
            } else {
                getString(R.string.member)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null // 避免内存泄漏
    }
}