package com.example.myapplication.ui.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.myapplication.R
import android.widget.LinearLayout
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.LoginResponse
import de.hdodenhof.circleimageview.CircleImageView
import android.util.Log
import kotlinx.coroutines.launch
import android.widget.TextView
import com.example.myapplication.utils.EncryptedSharedPreferencesUtil
import androidx.navigation.navOptions

class MineFragment : Fragment() {

    private lateinit var nickname: TextView
    private lateinit var time: TextView
    private lateinit var logout: TextView



    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_mine, container, false)
    }

    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 判断是否登录（门禁）
        if (!isLoggedIn()) {
            val nav = findNavController()

            // 改用 savedStateHandle 的标记：LoginFragment 返回时写入
            val fromLogin = nav.currentBackStackEntry
                ?.savedStateHandle
                ?.get<Boolean>("from_login") == true

            // 用完就清掉
            nav.currentBackStackEntry?.savedStateHandle?.remove<Boolean>("from_login")

            view?.post {
                try {
                    if (fromLogin) {
                        // 从登录页回来仍未登录：跳首页
                        nav.navigate(R.id.action_global_homeFragment)
                    } else {
                        // 不是从登录页来：跳登录
                        nav.navigate(R.id.action_mineFragment_to_loginFragment)
                    }
                } catch (e: IllegalArgumentException) {
                    // 万一你的导航框架在当前时机解析 action 有问题，兜底：直接去目标 Fragment id
                    if (fromLogin) {
                        nav.navigate(R.id.homeFragment)
                    } else {
                        nav.navigate(R.id.loginFragment)
                    }
                }
            }

            return
        }


        nickname = view.findViewById(R.id.nickname)
        time = view.findViewById(R.id.time)
        logout = view.findViewById(R.id.logout)


        // 获取用户信息, 并显示
        val user = EncryptedSharedPreferencesUtil.get(requireContext(), "Personal_information", LoginResponse::class.java)
        nickname.text = user?.nickName ?: ""
        time.text = user?.vipExpiry?.let { "Due on November $it" } ?: ""
        
        // 2) 下一帧再请求网络（让首帧先出来）
        view.post {
            viewLifecycleOwner.lifecycleScope.launch {
                try {
                    val response = RetrofitClient.apiService.getUser()
                    nickname.text = response.data?.nickName ?: ""
                    time.text = response.data?.vipExpiry?.let { "Due on November $it" } ?: ""
                    EncryptedSharedPreferencesUtil.save(requireContext(), "Personal_information", response.data)
                } catch (e: Exception) {
                    Log.e("1314520-MineFragment", "获取失败", e)
                }
            }
        }

        // 退出登录（先确认）
        logout.setOnClickListener {
            LogoutDialogFragment {
                // ✅ 用户确认后才执行
                EncryptedSharedPreferencesUtil.remove(requireContext(), "Personal_information")
                EncryptedSharedPreferencesUtil.remove(requireContext(), "user")

                // ⚠️ 建议用 popUpTo 清栈，避免按返回回到已登录页面
                findNavController().navigate(R.id.action_mineFragment_to_loginFragment)
            }.show(parentFragmentManager, "logout_dialog")
        }

        
        // 会员充值按钮点击
        view.findViewById<ImageView>(R.id.imgLeft).setOnClickListener {
            findNavController().navigate(R.id.action_global_rechargeFragment)
        }
        
        // 金币充值按钮点击
        view.findViewById<ImageView>(R.id.imgRight).setOnClickListener {
            findNavController().navigate(R.id.action_global_goldCoinRechargeFragment)
        }

        // 头像点击
        view.findViewById<CircleImageView>(R.id.avatar).setOnClickListener {
             findNavController().navigate(R.id.action_mineFragment_to_personalSettings)
        }

        //我的键盘
        view.findViewById<LinearLayout>(R.id.keyboard_settings).setOnClickListener {
            findNavController().navigate(R.id.action_mineFragment_to_mykeyboard)
       }
        
        // 反馈按钮点击
        view.findViewById<LinearLayout>(R.id.click_Feedback).setOnClickListener {
            findNavController().navigate(R.id.action_mineFragment_to_feedbackFragment)
       }

        // 反馈按钮点击
        view.findViewById<LinearLayout>(R.id.click_Notice).setOnClickListener {
            findNavController().navigate(R.id.action_mineFragment_to_notificationFragment)
       }

       //隐私政策
    //     view.findViewById<LinearLayout>(R.id.click_Privacy).setOnClickListener {
    //         findNavController().navigate(R.id.action_mineFragment_to_loginFragment)
    //    }
 
    }
    private fun isLoggedIn(): Boolean {
        return EncryptedSharedPreferencesUtil.contains(requireContext(), "user")
    }
}
