package com.gh.gamecenter.forum.home.follow.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.entity.PersonalHistoryEntity
import com.gh.gamecenter.feature.entity.AnswerEntity
import com.gh.gamecenter.feature.entity.Questions
import com.gh.gamecenter.forum.home.ForumArticleAskItemViewHolder
import com.gh.gamecenter.forum.home.follow.FollowDynamicBbsItem
import com.gh.gamecenter.forum.home.follow.FollowDynamicFooterItem
import com.gh.gamecenter.forum.home.follow.FollowDynamicItem
import com.gh.gamecenter.forum.home.follow.FollowDynamicItem.Companion.FOLLOW_DYNAMIC_ITEM_TYPE_BBS
import com.gh.gamecenter.forum.home.follow.FollowDynamicItem.Companion.FOLLOW_DYNAMIC_ITEM_TYPE_FOOTER
import com.gh.gamecenter.forum.home.follow.FollowDynamicItem.Companion.FOLLOW_DYNAMIC_ITEM_TYPE_PERSONAL
import com.gh.gamecenter.forum.home.follow.FollowDynamicPersonalItem
import com.gh.gamecenter.forum.home.follow.viewholder.FollowFooterViewHolder
import com.gh.gamecenter.forum.home.follow.viewholder.FollowInvalidViewHolder
import com.gh.gamecenter.forum.home.follow.viewmodel.FollowDynamicListViewModel
import com.gh.gamecenter.forum.home.follow.viewmodel.FollowDynamicViewModel
import com.gh.gamecenter.forum.search.CommunitySearchEventListener
import com.gh.gamecenter.personalhome.PersonalItemViewHolder

class FollowDynamicAdapter(
    private val context: Context,
    private val viewModel: FollowDynamicListViewModel
) : ListAdapter<FollowDynamicItem, ViewHolder>(createDiffCallback()) {

    private var _recyclerView: RecyclerView? = null
    private var loadStatus: LoadStatus? = null

    fun setLoadStatus(status: LoadStatus) {
        loadStatus = status
        notifyItemChanged(itemCount - 1)
    }

    override fun submitList(list: List<FollowDynamicItem>?) {
        val dataWithFooter = if (list.isNullOrEmpty()) {
            ArrayList(list)
        } else {
            list + FollowDynamicFooterItem
        }
        super.submitList(dataWithFooter)
    }

    override fun getItemViewType(position: Int): Int {
        return currentList[position].itemType
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return when (viewType) {
            FOLLOW_DYNAMIC_ITEM_TYPE_PERSONAL -> {
                FollowDynamicPersonalViewHolder(context, parent.toBinding()) { history, position ->
                    viewModel.navigateToPersonDetailPage(history, position)
                }
            }

            FOLLOW_DYNAMIC_ITEM_TYPE_BBS -> {
                FollowDynamicBbSViewHolder(parent.toBinding(), viewModel.bbsId) { position, answer ->
                    viewModel.navigateToBbsDetailPage(position, answer)
                }
            }

            FOLLOW_DYNAMIC_ITEM_TYPE_FOOTER ->
                FollowFooterViewHolder(parent.toBinding())

            else -> {
                FollowInvalidViewHolder(parent.toBinding())
            }
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        when (holder) {
            is FollowDynamicPersonalViewHolder -> {
                val item = getItem(position)
                if (item is FollowDynamicPersonalItem) {
                    holder.onBind(item.data, "", position)
                }
            }

            is FollowDynamicBbSViewHolder -> {
                val item = getItem(position)
                if (item is FollowDynamicBbsItem) {
                    holder.onBind(item.data, "", "", position)
                }
            }

            is FollowFooterViewHolder -> {
                holder.initFooterViewHolder(
                    loadStatus == LoadStatus.LIST_LOADING,
                    loadStatus == LoadStatus.LIST_FAILED,
                    loadStatus == LoadStatus.LIST_OVER,
                    R.string.load_over_with_click_hint
                ) {
                    if (loadStatus == LoadStatus.LIST_OVER) {
                        _recyclerView?.scrollToPosition(0)
                    } else if (loadStatus == LoadStatus.LIST_FAILED) {
                        viewModel.loadMore()
                        notifyItemChanged(itemCount - 1)
                    }
                }
            }

            else -> Unit
        }
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(onLoadMoreListener)
        _recyclerView = recyclerView
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        recyclerView.removeOnScrollListener(onLoadMoreListener)
        _recyclerView = null
    }

    private val onLoadMoreListener = object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                val layoutManger = recyclerView.layoutManager
                if (layoutManger is LinearLayoutManager && itemCount != 0) {
                    val lastVisibleItemPosition = layoutManger.findLastVisibleItemPosition()
                    if (lastVisibleItemPosition == itemCount - 1 && loadStatus != LoadStatus.LIST_OVER && loadStatus != LoadStatus.LIST_LOADING) {
                        viewModel.loadMore()
                    }
                }
            }
        }

    }

    companion object {
        fun createDiffCallback() = object : ItemCallback<FollowDynamicItem>() {
            override fun areItemsTheSame(oldItem: FollowDynamicItem, newItem: FollowDynamicItem): Boolean {
                return oldItem.areItemsTheSame(newItem)
            }

            override fun areContentsTheSame(oldItem: FollowDynamicItem, newItem: FollowDynamicItem): Boolean {
                return oldItem.areContentsTheSame(newItem)
            }

        }
    }

    class FollowDynamicPersonalViewHolder(
        private val context: Context,
        val binding: CommunityAnswerItemBinding,
        private val itemClickCallback: (historyEntity: PersonalHistoryEntity, position: Int) -> Unit
    ) :
        RecyclerView.ViewHolder(binding.root) {

        // 复用原有 viewHolder
        private val realViewHolder by lazy(LazyThreadSafetyMode.NONE) {
            PersonalItemViewHolder(context, binding, itemClickCallback)
        }

        fun onBind(historyEntity: PersonalHistoryEntity, entrance: String, position: Int) {
            realViewHolder.bindPersonalItem(historyEntity, entrance, position)
        }
    }

    class FollowDynamicBbSViewHolder(
        val binding: CommunityAnswerItemBinding,
        private val bbsId: String,
        private val onItemClick: (Int, AnswerEntity) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {

        private val viewHolder by lazy(LazyThreadSafetyMode.NONE) {
            ForumArticleAskItemViewHolder(binding)
        }

        fun onBind(answer: AnswerEntity, entrance: String, path: String, position: Int) {
            val articlePosition = position - 1
            if (answer.type != "answer") {
                val questions = Questions()
                questions.id = answer.id
                questions.title = answer.title
                questions.description = answer.description
                questions.answerCount = answer.count.answer
                answer.questions = questions
            }
            if (path == "精华" && answer.type != "answer" && answer.type != "video") answer.type = "community_article"
            if (path == "问答") answer.type = "question"
            if (path == "视频") answer.type = "video"

            if (answer.bbs.id.isEmpty()) answer.bbs.id = bbsId

            binding.forumNameLl.visibility = View.GONE
            binding.topLine.goneIf(articlePosition == 0)

            val params = binding.includeVoteAndComment.root.layoutParams as LinearLayout.LayoutParams
            params.width = LinearLayout.LayoutParams.MATCH_PARENT
            params.leftMargin = 0
            params.rightMargin = 0
            binding.includeVoteAndComment.root.layoutParams = params

            viewHolder.bindForumAnswerItem(answer, entrance, path, position)
            viewHolder.itemView.setOnClickListener {
                onItemClick(position, answer)
            }
        }
    }
}