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

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.databinding.RecyclerFollowHomeHeaderBinding
import com.gh.gamecenter.entity.FollowUserEntity
import com.gh.gamecenter.forum.home.follow.adapter.FollowedHeaderAdapter

class FollowHomeHeaderViewHolder(
    val binding: RecyclerFollowHomeHeaderBinding,
    val listener: OnEventListener
) : ViewHolder(binding.root) {

    private var data: List<FollowUserEntity> = listOf()

    private val followedHeaderAdapter by lazy {
        FollowedHeaderAdapter(itemView.context, object : FollowedHeaderAdapter.OnChildEventListener {
            override fun onViewItem(position: Int) {
                listener.onItemClick(position, data)
            }

            override fun onViewAll() {
                listener.onAllClick()
            }

        })
    }

    fun bind(isLogin: Boolean, followedList: List<FollowUserEntity>) {

        fun setViewsVisible(tipsGone: Boolean, recyclerGone: Boolean, loginGone: Boolean) {
            binding.tvNoDataTips.goneIf(tipsGone)
            binding.rvFollowed.goneIf(recyclerGone)
            binding.gLogin.goneIf(loginGone)
        }

        when {
            !isLogin -> {
                setViewsVisible(tipsGone = true, recyclerGone = true, loginGone = false)
                binding.tvLogin.setOnClickListener {
                    listener.onLoginClick()
                }
            }

            followedList.isEmpty() -> {
                setViewsVisible(tipsGone = false, recyclerGone = true, loginGone = true)
            }

            else -> {
                setViewsVisible(tipsGone = true, recyclerGone = false, loginGone = true)
                if (binding.rvFollowed.adapter == null) {
                    binding.rvFollowed.layoutManager =
                        LinearLayoutManager(itemView.context, RecyclerView.HORIZONTAL, false)
                    binding.rvFollowed.adapter = followedHeaderAdapter
                }
                data = followedList
                followedHeaderAdapter.submitList(followedList)
            }
        }
    }

    fun updateReadStatus(ids: List<String>) {
        val oldData = followedHeaderAdapter.dataList
        val newData = oldData.toMutableList()
        oldData.forEachIndexed { index, followUserEntity ->
            if (ids.contains(followUserEntity.id)) {
                val newItem = followUserEntity.copy(_isShowTip = 0)
                newData[index] = newItem
            }
        }
        data = newData
        followedHeaderAdapter.submitList(newData)
    }

    interface OnEventListener {

        fun onItemClick(position: Int, data: List<FollowUserEntity>)

        fun onAllClick()

        fun onLoginClick()
    }
}