package com.adealink.weparty.playmate.detail.comp

import android.animation.ArgbEvaluator
import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.graphics.toColorInt
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.aab.util.getCompatDimension
import com.adealink.frame.base.fastLazy
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.frame.mvvm.viewmodel.activityViewModels
import com.adealink.frame.router.Router
import com.adealink.frame.util.isActivityInValid
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.dialogfragment.CommonTextActionDialog
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.dpf
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.isFollowed
import com.adealink.weparty.module.setting.Setting
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.ActivityPlaymateDetailBinding
import com.adealink.weparty.playmate.detail.viewmodel.PlaymateDetailViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory
import com.adealink.weparty.util.QMUIStatusBarHelper
import com.adealink.weparty.util.applyImmersive
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.abs
import com.adealink.weparty.R as APP_R

class PlaymateToolBarViewComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: ActivityPlaymateDetailBinding
) : ViewComponent(lifecycleOwner) {

    private val detailViewModel by activityViewModels<PlaymateDetailViewModel> { PlaymateViewModelFactory() }
    private val followViewModel by fastLazy { ProfileModule.getFollowViewModel(requireActivity()) }

    private val blackViewModel by fastLazy { ProfileModule.getBlackViewModel(requireActivity()) }
    private var uid: String? = null
    private var isFollow: Boolean = false

    private val isSelf: Boolean
        get() {
            return uid == ProfileModule.getMyUid()
        }

    private var buttonIconColor = 0

    override fun onCreate() {
        super.onCreate()
        initView()
        observeViewModel()
    }

    @SuppressLint("UseKtx")
    private fun initView() {
        val activity = activity ?: return
        activity.applyImmersive { top ->
            val topbarHeight = top + getCompatDimension(APP_R.dimen.common_top_bar_height).toInt()
            binding.topBar.root.setPadding(16.dp(), top, 16.dp(), 0)
            binding.topBar.root.updateLayoutParams<MarginLayoutParams> {
                height = topbarHeight
            }
            binding.collapsingToolbarLayout.minimumHeight = topbarHeight
        }

        //顶部栏背景
        val fromColor = "#00FFFFFF".toColorInt()
        val toColor = "#FFFFFFFF".toColorInt()
        val topBarDrawable = ColorDrawable(fromColor)
        binding.topBar.root.background = topBarDrawable

        //顶部栏按钮背景
        val buttonBgFromColor = "#66000000".toColorInt()
        val buttonBgToColor = "#00000000".toColorInt()
        val buttonBgDrawable = GradientDrawable().apply {
            shape = GradientDrawable.OVAL
            setColor(buttonBgFromColor)
        }
        binding.topBar.btnFollow.background = buttonBgDrawable
        binding.topBar.btnHome.background = buttonBgDrawable
        binding.topBar.btnMore.background = buttonBgDrawable

        //按钮图标颜色
        val buttonIconFromColor = "#FFFFFFFF".toColorInt()
        val buttonIconToColor = "#FF000000".toColorInt()
        buttonIconColor = buttonIconFromColor

        //内容背景
        val fromRadius = 20.dpf()
        val toRadius = 0
        val contentDrawable = GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(Color.WHITE)
            cornerRadii = floatArrayOf(
                fromRadius, fromRadius, //top-left
                fromRadius, fromRadius, //top-right
                0f, 0f, //bottom-left
                0f, 0f //bottom-right
            )
        }
        binding.flContent.background = contentDrawable

        binding.appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            if (isActivityInValid(activity)) {
                return@OnOffsetChangedListener
            }
            val appBarHeight = appBarLayout?.height ?: return@OnOffsetChangedListener
            Log.d(TAG, "appBarHeight = $appBarHeight, verticalOffset = $verticalOffset")
            val percent =
                (abs(verticalOffset) * 1f / (appBarLayout.totalScrollRange)).coerceIn(0F, 1F)

            //顶部栏背景
            run {
                val color = ArgbEvaluator().evaluate(percent, fromColor, toColor) as Int
                topBarDrawable.color = color
            }

            //顶部栏按钮
            run {
                val color =
                    ArgbEvaluator().evaluate(percent, buttonBgFromColor, buttonBgToColor) as Int
                buttonBgDrawable.setColor(color)

                buttonIconColor =
                    ArgbEvaluator().evaluate(percent, buttonIconFromColor, buttonIconToColor) as Int
                binding.topBar.btnBack.drawable?.setTint(buttonIconColor)
                binding.topBar.btnFollow.drawable?.setTint(buttonIconColor)
                binding.topBar.btnHome.drawable?.setTint(buttonIconColor)
                binding.topBar.btnMore.drawable?.setTint(buttonIconColor)
            }

            //主体内容圆角变直角
            run {
                val radius = fromRadius + (toRadius - fromRadius) * percent
                contentDrawable.cornerRadii = floatArrayOf(
                    radius, radius, //top-left
                    radius, radius, //top-right
                    0f, 0f, //bottom-left
                    0f, 0f //bottom-right
                )
            }

            run {
                binding.topBar.ivAvatar.alpha = percent
                binding.topBar.tvUserName.alpha = percent
                if (percent >= 0.5f) {
                    QMUIStatusBarHelper.setStatusBarLightMode(activity)
                } else {
                    QMUIStatusBarHelper.setStatusBarDarkMode(activity)
                }
            }

        })

        binding.topBar.btnBack.onClick {
            activity.finish()
        }
        binding.topBar.btnHome.onClick {
            goProfile()
        }
    }

    private fun observeViewModel() {
        detailViewModel.detailLD.observe(viewLifecycleOwner) {
            this@PlaymateToolBarViewComp.uid = it?.uid
            binding.topBar.ivAvatar.setImageUrl(it?.avatar)
            binding.topBar.tvUserName.text = it?.nickname

            if (isSelf) {
                binding.topBar.btnMore.gone()
                binding.topBar.btnFollow.gone()
            } else {
                binding.topBar.btnMore.show()
                binding.topBar.btnMore.onClick {
                    clickMore()
                }
                binding.topBar.btnFollow.onClick {
                    clickFollow()
                }
            }
        }

        followViewModel?.isFollowLD?.observe(viewLifecycleOwner) {
            isFollow = it[this@PlaymateToolBarViewComp.uid]?.isFollowed() ?: false
            updateFollow()
        }
    }

    private fun goProfile() {
        val uid = this@PlaymateToolBarViewComp.uid
        if (uid.isNullOrEmpty()) {
            return
        }
        activity?.let { act ->
            Router.build(act, Profile.UserProfile.PATH)
                .putExtra(Profile.Common.EXTRA_UID, uid)
                .start()
        }
    }

    private fun clickFollow() {
        val uid = this@PlaymateToolBarViewComp.uid
        if (uid.isNullOrEmpty()) {
            return
        }
        if (isFollow) {
            followViewModel?.unFollow(uid)?.observe(viewLifecycleOwner) {
                showFailedToast(it)
            }
        } else {
            followViewModel?.follow(uid)?.observe(viewLifecycleOwner) {
                showFailedToast(it)
            }
        }
    }

    private fun updateFollow() {
        if (isFollow) {
            binding.topBar.btnFollow.gone()
            binding.topBar.btnFollow.setImageResource(R.drawable.playmate_followed_ic)
        } else {
            binding.topBar.btnFollow.show()
            binding.topBar.btnFollow.setImageResource(R.drawable.playmate_follow_ic)
        }
        binding.topBar.btnFollow.drawable?.setTint(buttonIconColor)
    }

    private fun clickMore() {
        val uid = uid ?: return
        val isBlack = blackViewModel?.isBlackLD?.value?.get(uid) ?: false
        CommonTextActionDialog.Builder()
            .addItem(APP_R.id.id_common_op_report, APP_R.string.common_report)
            .addItem(
                APP_R.id.id_common_op_black, if (isBlack) {
                    APP_R.string.common_remove_black
                } else {
                    APP_R.string.common_add_black
                }
            )
            .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                override fun onActionClick(viewId: Int) {
                    when (viewId) {
                        APP_R.id.id_common_op_report -> {
                            clickReport()
                        }

                        APP_R.id.id_common_op_black -> {
                            clickBlack()
                        }
                    }
                }
            }).build().show(fragmentManager)
    }

    private fun clickReport() {
        val uid = uid ?: return
        val act = activity ?: return
        Router.build(act, Setting.Report.PATH)
            .putExtra(Setting.Report.EXTRA_UID, uid)
            .start()
    }

    private fun clickBlack() {
        val uid = uid ?: return
        val isBlack = blackViewModel?.isBlackLD?.value?.get(uid) ?: false
        if (isBlack) {
            blackViewModel?.unBlack(uid)
        } else {
            blackViewModel?.black(uid)
        }
    }

    companion object {
        const val TAG = "PlaymateToolBarViewComp"
    }

}