package com.adealink.weparty.profile.comp

import android.animation.ArgbEvaluator
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.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.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.module.share.Share
import com.adealink.weparty.profile.databinding.ActivityUserProfileBinding
import com.adealink.weparty.profile.relation.viewmodel.BlackViewModel
import com.adealink.weparty.profile.relation.viewmodel.FollowViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModelFactory
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 ProfileToolBarViewComp(
    lifecycleOwner: LifecycleOwner,
    private val userUid: String,
    private val binding: ActivityUserProfileBinding
) : ViewComponent(lifecycleOwner) {

    companion object {
        const val TAG = "ProfileToolBarViewComp"
    }

    private val profileViewModel by activityViewModels<ProfileViewModel> { ProfileViewModelFactory() }
    private val followViewModel by activityViewModels<FollowViewModel> { ProfileViewModelFactory() }
    private val blackViewModel by activityViewModels<BlackViewModel> { ProfileViewModelFactory() }


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

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

    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 topbarFromColor = "#00FFFFFF".toColorInt()
        val topbarToColor = "#FFFFFFFF".toColorInt()
        val topBarDrawable = ColorDrawable(topbarFromColor)
        binding.topBar.root.background = topBarDrawable

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

        //编辑按钮背景
        val editButtonBgFromColor = "#66000000".toColorInt()
        val editButtonBgToColor = "#00000000".toColorInt()
        val editButtonBgDrawable = GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(editButtonBgFromColor)
            cornerRadii = floatArrayOf(
                20.dpf(), 20.dpf(), //top-left
                20.dpf(), 20.dpf(), //top-right
                20.dpf(), 20.dpf(), //bottom-left
                20.dpf(), 20.dpf() //bottom-right
            )
        }
        binding.topBar.btnEdit.background = editButtonBgDrawable

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

        //内容背景
        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.tabLayout.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, topbarFromColor, topbarToColor) as Int
                topBarDrawable.color = color
            }

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

            //顶部栏编辑按钮
            run {
                val color = ArgbEvaluator().evaluate(
                    percent,
                    editButtonBgFromColor,
                    editButtonBgToColor
                ) as Int
                editButtonBgDrawable.setColor(color)
            }

            //顶部栏按钮图标
            run {
                val color =
                    ArgbEvaluator().evaluate(percent, buttonIconFromColor, buttonIconToColor) as Int
                binding.topBar.ivBack.drawable?.setTint(color)
                binding.topBar.btnShare.drawable?.setTint(color)
                binding.topBar.btnMore.drawable?.setTint(color)
                binding.topBar.ivEdit.drawable?.setTint(color)
                binding.topBar.tvEdit.setTextColor(color)
            }

            //主体内容圆角变直角
            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.85f) {
                    QMUIStatusBarHelper.setStatusBarLightMode(activity)
                } else {
                    QMUIStatusBarHelper.setStatusBarDarkMode(activity)
                }
            }
        })

        binding.topBar.ivBack.onClick {
            activity.finish()
        }

        if (isSelf) {
            binding.topBar.btnShare.onClick {
                goShare()
            }
            binding.topBar.btnMore.gone()
            binding.topBar.btnEdit.show()
            binding.topBar.btnEdit.onClick {
                goEdit()
            }
        } else {
            binding.topBar.btnMore.show()
            binding.topBar.btnMore.onClick {
                clickMore()
            }
            binding.topBar.btnEdit.gone()
        }
    }


    private fun observeViewModel() {
        profileViewModel.userInfoLD.observe(viewLifecycleOwner) { userInfo ->
            binding.topBar.ivAvatar.setImageUrl(userInfo?.avatar)
            binding.topBar.tvUserName.text = userInfo?.nickName
            if (isSelf && userInfo?.isPlaymate() == true) {
                binding.topBar.btnShare.show()
            } else {
                binding.topBar.btnShare.gone()
            }
        }
    }

    private fun goShare() {
        activity?.let { act ->
            Router.build(act, Share.Poster.PATH).start()
        }
    }

    private fun clickMore() {
        val isFollow = followViewModel.isFollowLD.value?.get(userUid)?.isFollowed() ?: false
        val isBlack = blackViewModel.isBlackLD.value?.get(userUid) ?: false
        CommonTextActionDialog.Builder()
            .addItem(
                APP_R.id.id_common_op_follow, if (isFollow) {
                    APP_R.string.common_unfollow
                } else {
                    APP_R.string.common_follow
                }
            )
            .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_follow -> {
                            clickFollow()
                        }

                        APP_R.id.id_common_op_report -> {
                            clickReport()
                        }

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

    private fun clickFollow() {
        val isFollow = followViewModel.isFollowLD.value?.get(userUid)?.isFollowed() ?: false
        if (isFollow) {
            followViewModel.unFollow(userUid)
        } else {
            followViewModel.follow(userUid)
        }
    }

    private fun clickReport() {
        activity?.let { act ->
            Router.build(act, Setting.Report.PATH)
                .putExtra(Setting.Report.EXTRA_UID, userUid)
                .start()
        }
    }

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

    private fun goEdit() {
        activity?.let { act ->
            Router.build(act, Profile.EditProfile.PATH).start()
        }
    }

}