package com.gh.gamecenter.forum.home

import android.graphics.Bitmap
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import androidx.recyclerview.widget.RecyclerView
import com.ethanhua.skeleton.Skeleton
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.SpacingItemDecoration
import com.gh.gamecenter.core.iinterface.IScrollable
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.FragmentForumActivityBinding
import com.gh.gamecenter.databinding.LayoutForumActivityCategoryItemBinding
import com.gh.gamecenter.entity.ForumActivityCategoryEntity
import com.gh.gamecenter.entity.ForumActivityEntity
import com.google.android.flexbox.FlexboxLayout

class ForumActivityFragment : LazyListFragment<ForumActivityEntity, ForumActivityViewModel>(), IScrollable {

    private var mBinding: FragmentForumActivityBinding? = null
    private var mAdapter: ForumActivityAdapter? = null
    private var mCategoryBitmap: Bitmap? = null
    var translationY = 0

    override fun getRealLayoutId() = R.layout.fragment_forum_activity

    override fun provideListAdapter() =
        mAdapter ?: ForumActivityAdapter(requireContext(), mListViewModel, "论坛-活动").apply { mAdapter = this }

    override fun provideListViewModel(): ForumActivityViewModel {
        return viewModelProvider()
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        mBinding = FragmentForumActivityBinding.bind(inflatedView)
    }

    override fun initRealView() {
        super.initRealView()

        initSkeleton()

        mListViewModel.categories.observeNonNull(viewLifecycleOwner) {
            initCategoryView(ArrayList(it))
        }

        mListRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                translationY = recyclerView.computeVerticalScrollOffset()
                (parentFragment as? CommunityHomeFragment)?.translateTopBg(translationY)
                changeCategoryBg()
            }
        })
    }

    override fun onRefresh() {
        mBinding?.categoryContainer?.visibility = View.GONE
        super.onRefresh()
    }

    override fun onLoadDone() {
        super.onLoadDone()
        if (mAdapter?.hasCategory == true) {
            mBinding?.categoryContainer?.visibility = View.VISIBLE
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        NewLogUtils.logForumActivityEnter()
    }

    private fun initSkeleton() {
        mSkeletonScreen = Skeleton.bind(mBinding?.listSkeleton)
            .shimmer(true)
            .angle(Constants.SHIMMER_ANGLE)
            .color(com.gh.gamecenter.common.R.color.ui_skeleton_highlight)
            .duration(Constants.SHIMMER_DURATION)
            .maskWidth(Constants.MASK_WIDTH)
            .gradientCenterColorWidth(Constants.GRADIENT_CENTER_COLOR_WIDTH)
            .load(R.layout.fragment_forum_activity_skeleton)
            .show()
    }

    override fun getItemDecoration() =
        SpacingItemDecoration(notDecorateTheFirstItem = true, top = if (mIsDarkModeOn) 16F.dip2px() else 6F.dip2px())

    private fun initCategoryView(list: ArrayList<ForumActivityCategoryEntity>) {
        if (list.isEmpty()) return

        mAdapter?.hasCategory = true
        mBinding?.categoryContainer?.visibility = View.VISIBLE

        (parentFragment as? CommunityHomeFragment)?.run {
            mBinding?.run {
                categoryContainer.post {
                    val bitmap = getTopBgView()?.getBitmapFromView()
                    bitmap?.let {
                        mCategoryBitmap = Bitmap.createBitmap(
                            it,
                            0,
                            DisplayUtils.getStatusBarHeight(resources) + 52f.dip2px(),
                            it.width,
                            categoryContainer.height
                        )
                    }
                }
            }
        }

        list.add(0, ForumActivityCategoryEntity(id = "", name = "全部"))
        list.forEachIndexed { index, entity ->
            val binding = LayoutForumActivityCategoryItemBinding.inflate(layoutInflater).apply {
                val params =
                    FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                params.setMargins(0, 8F.dip2px(), 8F.dip2px(), 0)
                params.height = 24F.dip2px()
                root.layoutParams = params

                name.text = entity.name
                name.isChecked = index == 0
                root.setOnClickListener {
                    NewLogUtils.logForumActivityCategoryClick(entity.id)
                    updateCategory(index, entity)
                }
            }

            mBinding?.categoryContainer?.addView(binding.root)
        }
    }

    private fun updateCategory(index: Int, entity: ForumActivityCategoryEntity) {
        updateCategoryView(index)
        mListViewModel.categoryId = entity.id
        onRefresh()
    }

    private fun updateCategoryView(index: Int) {
        mBinding?.categoryContainer?.run {
            for (i in 0 until childCount) {
                val categoryView = getChildAt(i) as CheckedTextView
                categoryView.isChecked = index == i
            }
        }
    }

    fun changeCategoryBg() {
        mBinding?.run {
            if (categoryContainer.visibility != View.VISIBLE) return
            if (translationY != 0) {
                if (!mIsDarkModeOn && categoryBg.drawable == null) {
                    categoryBg.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
                    categoryBg.setImageBitmap(mCategoryBitmap)
                } else if (mIsDarkModeOn) {
                    categoryBg.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
                    categoryBg.setImageDrawable(null)
                }
            } else {
                categoryBg.setBackgroundColor(
                    if (mIsDarkModeOn) com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()) else com.gh.gamecenter.common.R.color.transparent.toColor(
                        requireContext()
                    )
                )
                categoryBg.setImageDrawable(null)
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if ((mListRv?.itemDecorationCount ?: 0) > 0) {
            mListRv?.removeItemDecorationAt(0)
            mListRv?.addItemDecoration(itemDecoration)
        }
        mListRv?.adapter?.let { it.notifyItemRangeChanged(0, it.itemCount) }
        (parentFragment as? CommunityHomeFragment)?.run {
            mBinding?.run {
                initSkeleton()
                showSkeleton(mListViewModel.loadStatusLiveData.value == LoadStatus.INIT_LOADING)
                categoryContainer.post {
                    val bitmap = getTopBgView()?.getBitmapFromView()
                    bitmap?.let {
                        mCategoryBitmap = Bitmap.createBitmap(
                            it,
                            0,
                            DisplayUtils.getStatusBarHeight(resources) + 52f.dip2px(),
                            it.width,
                            categoryContainer.height
                        )
                    }
                }
            }
            translateTopBg(translationY)
        }
        changeCategoryBg()
    }

    override fun scrollToTop() {
        mBinding?.listRv?.let {
            if (it.visibility == View.VISIBLE) {
                it.scrollToPosition(0)
            }
        }
    }
}