package com.gh.gamecenter.home.custom.viewholder

import android.content.Context
import android.view.ViewGroup
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.GameGallerySlideItemCustomBinding
import com.gh.gamecenter.databinding.ItemWithinGameGallerySlideCustomBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureProvider
import com.gh.gamecenter.home.custom.CustomPageViewModel
import com.gh.gamecenter.home.custom.eventlistener.SubjectEventHelper
import com.gh.gamecenter.home.custom.model.CustomPageItem
import com.gh.gamecenter.home.custom.model.CustomSubjectItem
import com.lightgame.adapter.BaseRecyclerAdapter

/**
 * 游戏专题-横向滚动图集
 * 游戏专题-图集滚动-v2
 */
class CustomGameGallerySlideViewHolder(
    viewModel: CustomPageViewModel,
    val binding: GameGallerySlideItemCustomBinding,
    private val lifecycleOwner: LifecycleOwner,
) : BaseCustomViewHolder(viewModel, binding.root), DefaultLifecycleObserver {

    private var cachedSubject: SubjectEntity? = null

    override val childEventHelper by lazy(LazyThreadSafetyMode.NONE) {
        SubjectEventHelper(viewModel)
    }

    override fun bindView(item: CustomPageItem) {
        super.bindView(item)
        if (item is CustomSubjectItem) {
            binding.cardView.setCardBackgroundColor(com.gh.gamecenter.common.R.color.ui_container_1.toColor(binding.root.context))
            if (item.data == cachedSubject) return

            cachedSubject = item.data
            setSubjectTitle(binding.layoutTitle, item, childEventHelper)
            val rvList =
                arrayListOf(binding.firstRecyclerView, binding.secondRecyclerView, binding.thirdRecyclerView)

            runOnIoThread(isLightWeightTask = true) {
                cachedSubject?.data?.forEachIndexed { index, gameEntity ->
                    fillExposureAndReportAd(gameEntity, index, item)
                }
            }

            for ((index, recyclerView) in rvList.withIndex()) {
                if (recyclerView.adapter == null) {
                    recyclerView.layoutManager =
                        LinearLayoutManager(binding.root.context, RecyclerView.HORIZONTAL, false)
                    recyclerView.adapter = GameGallerySlideAdapter(binding.root.context, index)
                    recyclerView.isNestedScrollingEnabled = false
                }
                val gameList = item.data.data ?: emptyList()
                (recyclerView.adapter as? GameGallerySlideAdapter)?.submitList(gameList)
            }
        }
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        binding.container.onResume(owner)
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        binding.container.onPause(owner)
    }

    override fun onViewAttach(parent: RecyclerView?) {
        super.onViewAttach(parent)
        lifecycleOwner.lifecycle.addObserver(binding.container)
    }

    override fun onViewDetach(parent: RecyclerView?) {
        super.onViewDetach(parent)
        lifecycleOwner.lifecycle.removeObserver(binding.container)
    }

    inner class GameGallerySlideAdapter(
        context: Context,
        private val index: Int,
    ) : BaseRecyclerAdapter<GameGallerySlideAdapter.GameGallerySlideItemViewHolder>(context) {

        private val dataList = arrayListOf<GameEntity>()
        fun submitList(data: List<GameEntity>) {
            dataList.clear()
            dataList.addAll(data)
            notifyDataSetChanged()
        }

        override fun getItemCount() = Int.MAX_VALUE

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameGallerySlideItemViewHolder {
            return GameGallerySlideItemViewHolder(parent.toBinding())
        }

        override fun onBindViewHolder(holder: GameGallerySlideItemViewHolder, position: Int) {
            if (dataList.isEmpty()) return

            val dataPosition = position * 3 + index
            val realPosition = dataPosition % dataList.size
            val gameEntity = dataList[realPosition]

            holder.bindView(realPosition, gameEntity)
        }

        inner class GameGallerySlideItemViewHolder(val binding: ItemWithinGameGallerySlideCustomBinding) :
            BaseRecyclerViewHolder<Any>(binding.root), IExposureProvider {
                var boundedGameEntity: GameEntity? = null

            fun bindView(realPosition: Int, gameEntity: GameEntity) {
                boundedGameEntity = gameEntity
                binding.iconIv.displayGameIconWithIfShowSubscript(
                    gameEntity,
                    cachedSubject?.showIndexIconSubscript ?: false
                )
                binding.iconIv.setOnClickListener {
                    childEventHelper.navigateToGameDetailPage(realPosition, gameEntity)
                }
            }

            override fun provideExposureData(): ExposureEvent? {
                return boundedGameEntity?.exposureEvent?.getFreshExposureEvent()
            }
        }
    }

}