package com.remax.visualnovel.ui.chat.message.detail.flirting

/**
 * Created by HJW on 2025/8/16
 */
import android.annotation.SuppressLint
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.airbnb.lottie.LottieAnimationView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.remax.visualnovel.R
import com.remax.visualnovel.app.base.BaseBindingActivity
import com.remax.visualnovel.app.delegate.isFull
import com.remax.visualnovel.app.delegate.titleTextAlpha
import com.remax.visualnovel.app.widget.tips.TipsSwitchWindow
import com.remax.visualnovel.entity.request.AIIsShowDTO
import com.remax.visualnovel.entity.response.HeartbeatLevel
import com.remax.visualnovel.extension.addScrollerAlpha
import com.remax.visualnovel.extension.getTemperatureTxt
import com.remax.visualnovel.extension.glide.loadAndRoundCorner
import com.remax.visualnovel.extension.launchAndLoadingCollect
import com.remax.visualnovel.extension.setMargin
import com.remax.visualnovel.extension.setOnClick
import com.remax.visualnovel.extension.setSize
import com.remax.visualnovel.extension.setSpanTypeFace
import com.remax.visualnovel.extension.showMoreTxtDialog
import com.remax.visualnovel.extension.translationYObjectAnimator
import com.remax.visualnovel.utils.Routers
import com.remax.visualnovel.utils.spannablex.spannable
import com.remax.visualnovel.utils.spannablex.utils.dp
import com.remax.visualnovel.widget.ui.UserAvatarView
import com.remax.visualnovel.widget.uitoken.changeTextFont
import com.remax.visualnovel.widget.uitoken.handleUIToken
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.divider
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.remax.visualnovel.databinding.ActivityFlirtingLevelBinding
import com.remax.visualnovel.databinding.ItemFlirtingLevelBinding
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber

@AndroidEntryPoint
@Route(path = Routers.CHAT_FLIRTING_LEVEL)
class FlirtingLevelActivity : BaseBindingActivity<ActivityFlirtingLevelBinding>() {

    private val flirtingLevelViewModel by viewModels<FlirtingLevelViewModel>()

    @JvmField
    @Autowired
    var aiId = ""

    @SuppressLint("SetTextI18n")
    override fun initView() {
        ARouter.getInstance().inject(this)
        setToolbar(R.string.app_name) {
            isFull = true
            titleTextAlpha = 1f
            setRightIconBtn1(R.string.icon_more) {
                val switchWindow = TipsSwitchWindow()
                switchWindow.build(
                    this@FlirtingLevelActivity,
                    R.string.hide_relations,
                    flirtingLevelViewModel.levelOutput?.aiUserHeartbeatRelation?.isShow != true
                ) { switchView, isChecked ->
                    launchAndLoadingCollect({
                        flirtingLevelViewModel.relationSwitch(AIIsShowDTO(aiId, if (isChecked) 0 else 1))
                    }) {
                        onSuccess = {
                            with(binding) {
                                listOf(tvMeet, dividerMeet1, dividerMeet2).forEach { view ->
                                    view.isGone =
                                        flirtingLevelViewModel.levelOutput?.aiUserHeartbeatRelation?.isShow != true
                                }
                            }
                        }

                        onFailed = { _, _ ->
                            switchView.isChecked = !isChecked
                        }
                    }
                }
                switchWindow.showAsDropDown(this)
            }

            setRightIconBtn2(R.string.icon_faq) {
                showMoreTxtDialog(
                    texts = listOf(
                        R.string.flirting_tips_txt_1,
                        R.string.flirting_tips_txt_2,
                        R.string.flirting_tips_txt_3
                    ).map { getString(it) })
            }
        }
        with(binding) {
            scrollView.addScrollerAlpha(aiAvatarView, includeBgAlpha = true, textAlpha = false)

            tvMeet.text = "· ${getString(R.string.meet)} ·"

            setOnClick(retrieveGroup) {
                flirtingLevelViewModel.levelOutput?.aiUserHeartbeatRelation?.let {
                    val retrieveDialog = FlirtingRetrieveDialog(this@FlirtingLevelActivity)
                    retrieveDialog.build(it) {
                        launchAndLoadingCollect({
                            flirtingLevelViewModel.buyHeartbeatVal(aiId)
                        }) {
                            onSuccess = {
                                initData()
                                retrieveDialog.dismiss()
                            }
                        }
                    }
                    retrieveDialog.binding.run {
                        showHeartAnim(levelBg, levelBgTop, lottieView, 84f)
                    }
                    retrieveDialog.show()
                }
            }

            rv.grid(2)
                .divider {
                    setDivider(16, true)
                    orientation = DividerOrientation.VERTICAL
                }.setup {
                    addType<HeartbeatLevel>(R.layout.item_flirting_level)
                    onBind {
                        val item = getModel<HeartbeatLevel>()
                        with(getBinding<ItemFlirtingLevelBinding>()) {
                            tvName.text = item.name
                            tvName.isEnabled = item.isUnlock
                            lockView.isVisible = !item.isUnlock
                            imageView.loadAndRoundCorner(item.imgUrl, 16)
                            tvTemperature.text = item.startVal.getTemperatureTxt()
                            tvTemperature.isEnabled = item.isUnlock
                            imageStroke.isVisible = item.isUnlock
                        }
                    }
                }
        }
    }

    @SuppressLint("SetTextI18n", "DefaultLocale")
    override fun initData() {
        launchAndLoadingCollect({
            flirtingLevelViewModel.getHeartbeatLevel(aiId)
        }) {
            onSuccess = {
                val relation = it?.aiUserHeartbeatRelation
                with(binding) {
                    listOf(tvMeet, dividerMeet1, dividerMeet2).forEach { view ->
                        view.isGone = relation?.isShow != true
                    }

                    showHeartAnim(levelBg, levelBgTop, lottieView, avatarView = aiAvatarView)

                    aiAvatarView.loadAvatar(relation?.aiHeadImg)
                    myAvatarView.loadAvatar(relation?.userHeadImg)
                    val currHeartbeat = relation?.currHeartbeatEnum
                    if (currHeartbeat == null) {
                        tvMeet.changeTextFont {
                            textUITextToken = getString(R.string.txt_title_s)
                        }
                        tvMeet.setText(R.string.no_intention_yet)
                    } else {
                        tvMeet.changeTextFont {
                            textUITextToken = getString(R.string.txt_display_s)
                        }
                        tvMeet.setText(currHeartbeat.tagName)
                    }
                    val heartbeatScore = String.format("%.2f", (relation?.heartbeatScore ?: 0.0f) * 100)

                    tvMeetDesc.text =
                        getString(R.string.flirting_desc, relation?.dayCount ?: 0, heartbeatScore)
                    tvLevel.text = spannable {
                        if (currHeartbeat != null) {
                            currHeartbeat.levelContent.text()
                            " 丨 ".color(handleUIToken(R.string.color_outline_normal)?.color ?: 0)
                        }
                        (relation?.heartbeatVal ?: 0.0).toString().text()
                        getString(R.string.temperature).span {
                            setSpanTypeFace(this@FlirtingLevelActivity, R.string.txt_numMonotype_s)
                        }
                    }

                    /**
                     * 已经扣减的心动分
                     */
                    retrieveGroup.isVisible = (relation?.subtractHeartbeatVal ?: 0.0) != 0.0
                    retrieveTitle.text =
                        getString(R.string.flirting_deducted_desc, (relation?.subtractHeartbeatVal ?: 0.0).toString())

                    rv.models = it?.heartbeatLeveLDictList
                }
            }
        }
    }

    private fun showHeartAnim(
        levelBg: View,
        levelBgTop: View,
        heartLottie: LottieAnimationView,
        bgBottomMargin: Float = 0f,
        avatarView: UserAvatarView? = null,
    ) {
        levelBg.post {
            val currProgress =
                flirtingLevelViewModel.levelOutput?.aiUserHeartbeatRelation?.currHeartbeatEnum?.level ?: 0
            val progress = currProgress / 10f

            // 弹窗中的切图需要往上移动
            levelBg.setMargin(bottomMargin = -((bgBottomMargin / 400f) * levelBgTop.measuredHeight).toInt())

            // 根据切图比例调整宽高
            val heartSize = ((98f / 214f) * levelBgTop.measuredHeight).toInt()
            heartLottie.setSize(heartSize, heartSize)

            // 头像框距离顶部的边距
            val marginTop = ((120f / 214f) * levelBgTop.measuredHeight) + (heartSize - 64.dp) / 2f
            avatarView?.setMargin(topMargin = marginTop.toInt())
            avatarView?.isVisible = true
            binding.myAvatarView.isVisible = true

            // 动画持续时间
            val totalTime = 1000L
            // 总高度进度算
            val totalHeight = progress * heartSize
            Timber.i("showHeartAnim  heartSize:$heartSize  totalHeight:$totalHeight")
            heartLottie.translationYObjectAnimator(-totalHeight, totalTime)
        }
    }

    companion object {
        fun start(aiId: String?) {
            if (aiId != null) {
                ARouter.getInstance()
                    .build(Routers.CHAT_FLIRTING_LEVEL)
                    .withString("aiId", aiId)
                    .navigation()
            }
        }
    }

}