package com.gh.gamecenter.qa.article.detail

import android.content.Context
import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.UnAvaliableWebviewViewHolder
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.databinding.TabItemBinding
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.visibleIf
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.FragmentWebWarningBinding
import com.gh.gamecenter.databinding.ItemArticleDetailCommentPagerBinding
import com.gh.gamecenter.databinding.ItemArticleDetailContentBinding
import com.gh.gamecenter.qa.comment.base.BaseCommentAdapter
import com.gh.gamecenter.qa.comment.base.BaseCommentViewModel
import com.google.android.material.tabs.TabLayout

class ArticleDetailAdapter(
    context: Context,
    private val mFragmentManager: FragmentManager,
    var mViewModel: ArticleDetailViewModel,
    var type: AdapterType,
    var entrance: String
) :
    BaseCommentAdapter(context, mViewModel, type, entrance) {

    var articleDetailVH: ArticleDetailContentViewHolder? = null

    override fun loadChange(status: LoadStatus?) {
        if (status == LoadStatus.INIT) {
            mIsNetworkError = false
            mIsOver = false
            mIsLoading = true
            return
        } else {
            super.loadChange(status)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            ITEM_ARTICLE_DETAIL -> {
                val isWebViewInstalled = PackageUtils.checkWebViewIsAvailable(mContext)
                if (isWebViewInstalled) {
                    val binding: ItemArticleDetailContentBinding =
                        ItemArticleDetailContentBinding.inflate(mLayoutInflater, parent, false)
                    ArticleDetailContentViewHolder(binding, mViewModel).apply { articleDetailVH = this }
                } else {
                    val binding: FragmentWebWarningBinding =
                        FragmentWebWarningBinding.inflate(mLayoutInflater, parent, false)
                    UnAvaliableWebviewViewHolder(binding)
                }
            }

            ITEM_COMMENT_PAGER -> {
                val binding: ItemArticleDetailCommentPagerBinding = parent.toBinding()
                CommentPagerViewHolder(mFragmentManager, mViewModel, type, entrance, binding)
            }

            else -> super.onCreateViewHolder(parent, viewType)
        }
    }

    override fun getItemViewType(position: Int): Int {
        if (mEntityList[position].commentPagerData != null) {
            return ITEM_COMMENT_PAGER
        }
        return super.getItemViewType(position)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is ArticleDetailContentViewHolder -> {
                holder.bindView(mEntityList[position].articleDetail!!)
            }

            is UnAvaliableWebviewViewHolder -> {
                holder.bindView(480f)
            }

            is CommentFilterViewHolder -> {
                holder.bindView(mViewModel.detailEntity)
            }

            is CommentPagerViewHolder -> {
                holder.bindView(mEntityList[position].commentPagerData!!)

            }

            else -> super.onBindViewHolder(holder, position)
        }
    }

    class CommentPagerViewHolder(
        val fragmentManager: FragmentManager,
        val viewModel: ArticleDetailViewModel,
        val type: AdapterType,
        val entrance: String,
        val binding: ItemArticleDetailCommentPagerBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        private lateinit var commentTab: TextView

        private var currentTotalNum: Int = -1

        fun initView(pagerData: CommentItemData.CommentPagerData) {
            val pagerAdapter = ArticleDetailCommentPagerAdapter(fragmentManager, entrance, pagerData.showRelatedContent)

            val tabLayout = binding.fragmentTabLayout
            val tabIndicator = binding.fragmentTabIndicator

            val viewPager = binding.fragmentViewPager
            viewPager.adapter = pagerAdapter
            viewPager.offscreenPageLimit = pagerAdapter.tabList.size
            viewPager.addOnPageChangeListener(object : OnPageChangeListener {

                override fun onPageSelected(position: Int) {
                    binding.orderSfv.visibleIf(position == 0)
                }

                override fun onPageScrollStateChanged(state: Int) = Unit

                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) = Unit

            })

            tabLayout.setupWithViewPager(viewPager)
            tabIndicator.setupWithTabLayout(tabLayout)
            tabIndicator.setupWithViewPager(viewPager)
            tabIndicator.setIndicatorWidth(20)
            tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    updateTabStyle(tab)
                }

                override fun onTabUnselected(tab: TabLayout.Tab) {
                    updateTabStyle(tab)
                }

                override fun onTabReselected(tab: TabLayout.Tab) {
                    updateTabStyle(tab)
                }
            })
            initTabLayout(pagerAdapter, tabLayout)

            binding.orderSfv.setItemList(listOf("正序", "倒序"), 0)
            binding.orderSfv.setOnCheckedCallback { position ->
                val newSort = if (position == 0) {
                    BaseCommentViewModel.SortType.OLDEST
                } else {
                    BaseCommentViewModel.SortType.LATEST
                }
                val newSortName = if (position == 0) "正序" else "倒序"

                viewModel.changeSort(newSort)

                if (viewModel.detailEntity == null) {
                    MtaHelper.onEvent("帖子详情", "全部评论", newSortName)
                } else {
                    MtaHelper.onEvent("帖子详情", "评论详情-全部回复", newSortName)
                }
            }
        }

        fun bindView(pagerData: CommentItemData.CommentPagerData) {
            if (binding.fragmentViewPager.adapter == null) {
                initView(pagerData)
            } else {
                updateView()
            }

            commentTab.text = binding.root.context.getString(
                R.string.article_detail_comment_list_tab_title,
                pagerData.totalCommentNum
            )
            if (currentTotalNum != pagerData.totalCommentNum) {// 只有totalCommentNum发生变化时才自动改变tab选中位置
                currentTotalNum = pagerData.totalCommentNum
                val currentItem = if (!pagerData.showRelatedContent || pagerData.totalCommentNum > 0) {// 评论列表为空时默认展示相关列表
                    ArticleDetailCommentPagerAdapter.POSITION_COMMENT_LIST
                } else {
                    ArticleDetailCommentPagerAdapter.POSITION_RELATED_CONTENTS
                }
                binding.fragmentViewPager.setCurrentItem(currentItem, false)
            }
        }

        private fun updateView() {
            binding.orderSfv.setContainerBackground(
                ContextCompat.getDrawable(
                    itemView.context,
                    com.gh.gamecenter.common.R.drawable.button_round_f5f5f5
                )
            )
            binding.orderSfv.setIndicatorBackground(
                ContextCompat.getDrawable(
                    itemView.context,
                    R.drawable.bg_game_collection_sfv_indicator
                )
            )
            binding.orderSfv.setTextColor(
                ContextCompat.getColor(
                    itemView.context,
                    com.gh.gamecenter.common.R.color.text_secondary,
                ),
                ContextCompat.getColor(
                    itemView.context,
                    com.gh.gamecenter.common.R.color.text_tertiary,
                )
            )
            updateTabLayout(binding.fragmentTabLayout)
        }

        private fun initTabLayout(pagerAdapter: ArticleDetailCommentPagerAdapter, tabLayout: TabLayout) {
            for (i in 0 until tabLayout.tabCount) {
                val tab: TabLayout.Tab = tabLayout.getTabAt(i) ?: continue
                val binding = TabItemBinding.inflate(LayoutInflater.from(binding.root.context), tab.view, false)
                if (i == 0) commentTab = binding.tabTitle
                binding.tabTitle.text = pagerAdapter.tabList[i]
                tab.customView = binding.root
                updateTabStyle(tab)
            }
        }

        private fun updateTabLayout(tabLayout: TabLayout) {
            for (i in 0 until tabLayout.tabCount) {
                val tab: TabLayout.Tab = tabLayout.getTabAt(i) ?: continue
                updateTabStyle(tab)
            }
        }

        private fun updateTabStyle(tab: TabLayout.Tab) {
            tab.customView?.findViewById<TextView>(R.id.tab_title)?.run {
                textSize = 14F
                typeface = if (tab.isSelected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
                setTextColor(
                    ContextCompat.getColor(
                        context,
                        if (tab.isSelected) com.gh.gamecenter.common.R.color.text_theme else com.gh.gamecenter.common.R.color.text_secondary
                    )
                )
            }
        }
    }

    companion object {
        const val ITEM_COMMENT_PAGER = 808
    }
}