package com.example.myapplication.ui.home

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.myapplication.R
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.CharacterDetailResponse
import kotlinx.coroutines.launch
import com.example.myapplication.network.AddPersonaClick

class PersonaDetailDialogFragment : DialogFragment() {

    companion object {
        private const val ARG_ID = "arg_persona_id"

        fun newInstance(personaId: Int): PersonaDetailDialogFragment {
            return PersonaDetailDialogFragment().apply {
                arguments = Bundle().apply { putInt(ARG_ID, personaId) }
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), R.style.PersonaDetailDialog) // 下面会给 style
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_persona_detail, null, false)
        dialog.setContentView(view)
        dialog.setCanceledOnTouchOutside(true)

        val personaId = requireArguments().getInt(ARG_ID)

        val btnClose = view.findViewById<ImageView>(R.id.btnClose)
        val ivAvatar = view.findViewById<de.hdodenhof.circleimageview.CircleImageView>(R.id.ivAvatar)
        val tvName = view.findViewById<TextView>(R.id.tvName)
        val tvBackground = view.findViewById<TextView>(R.id.tvBackground)
        val btnAdd = view.findViewById<TextView>(R.id.btnAdd)
        val download = view.findViewById<TextView>(R.id.download)

        btnClose.setOnClickListener { dismissAllowingStateLoss() }

        // ✅ 拉详情 - 使用lifecycleScope而不是viewLifecycleOwner
        lifecycleScope.launch {
            try {
                val resp = RetrofitClient.apiService.characterDetail(personaId)
                val data = resp.data


                if (data == null) {
                    return@launch
                }

                tvName.text = data.characterName ?: ""
                download.text = data.download ?: ""
                tvBackground.text = data.characterBackground ?: ""
                btnAdd.text = data.added?.let { "Added" } ?: "Add"
                btnAdd.setBackgroundResource(data.added?.let { R.drawable.ic_added } ?: R.drawable.keyboard_ettings)

                Glide.with(requireContext())
                    .load(data.avatarUrl)
                    .placeholder(R.drawable.default_avatar)
                    .error(R.drawable.default_avatar)
                    .into(ivAvatar)

                btnAdd.setOnClickListener {
                    lifecycleScope.launch {
                        if(data.added == true){
                            //取消收藏
                            data.id?.let { id ->
                                try {
                                    RetrofitClient.apiService.delUserCharacter(id.toInt())
                                } catch (e: Exception) {
                                    // 处理错误
                                }
                            }
                        }else{
                            val addPersonaRequest = AddPersonaClick(
                                characterId = data.id?.toInt() ?: 0,
                                emoji = data.emoji ?: ""
                            )
                            try {
                                RetrofitClient.apiService.addUserCharacter(addPersonaRequest)
                            } catch (e: Exception) {
                                // 处理错误
                            }
                        }
                        dismissAllowingStateLoss()
                    }
                }
            } catch (e: Exception) {
            }
        }

        return dialog
    }

    override fun onStart() {
        super.onStart()
        // 让弹窗宽度接近屏幕
        dialog?.window?.setLayout(
            (resources.displayMetrics.widthPixels * 0.92f).toInt(),
            WindowManager.LayoutParams.WRAP_CONTENT
        )
    }
}
