package com.adealink.weparty.playmate.detail.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.LifecycleOwner
import androidx.viewpager.widget.ViewPager
import com.adealink.frame.base.fastLazy
import com.adealink.frame.image.view.NetworkImageView
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.getActivity
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.BindingViewHolder
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.adapter.multitype.ItemViewBinder
import com.adealink.weparty.commonui.recycleview.layoutmanager.FlowLayoutManager
import com.adealink.weparty.commonui.viewpager.RecyclePagerAdapter
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.ItemPlaymateDetailContentBinding
import com.adealink.weparty.playmate.databinding.LayoutPlaymateDetailBannerItemBinding
import com.adealink.weparty.playmate.detail.data.PlaymateDetailImg
import com.adealink.weparty.playmate.detail.data.PlaymateDetailItemData
import com.adealink.weparty.playmate.detail.data.PlaymateDetailLabel
import com.adealink.weparty.util.goImagePreviewActivity

class PlaymateDetailViewBinder(
    val lifecycleOwner: LifecycleOwner
) : ItemViewBinder<PlaymateDetailItemData, PlaymateDetailViewBinder.ViewHolder>() {

    override fun onCreateViewHolder(
        inflater: LayoutInflater,
        parent: ViewGroup
    ): ViewHolder {
        return ViewHolder(ItemPlaymateDetailContentBinding.inflate(inflater, parent, false)).apply {
            initView()
        }
    }

    override fun onBindViewHolder(
        holder: ViewHolder,
        item: PlaymateDetailItemData
    ) {
        holder.update(item)
    }

    override fun onViewDetachedFromWindow(holder: ViewHolder) {
        super.onViewDetachedFromWindow(holder)
        holder.binding.vSound.stopPlay()
    }

    override fun onViewRecycled(holder: ViewHolder) {
        super.onViewRecycled(holder)
        holder.binding.vSound.stopPlay()
    }

    inner class ViewHolder(
        rootBinding: ItemPlaymateDetailContentBinding,
    ) : BindingViewHolder<ItemPlaymateDetailContentBinding>(rootBinding) {

        private val labelAdapter by fastLazy { MultiTypeListAdapter<PlaymateDetailLabel>() }

        private val viewAdapter by fastLazy { ViewAdapter() }

        private var itemData: PlaymateDetailItemData? = null
        fun initView() {
            labelAdapter.register(PlaymateLabelViewBinder())
            binding.rvLabel.adapter = labelAdapter
            binding.rvLabel.layoutManager =FlowLayoutManager(
                FlowLayoutManager.VERTICAL,
                6.dp(),
                10.dp()
            )

            binding.bannerImg.pageMargin = 10.dp()
            binding.bannerImg.offscreenPageLimit = 3
            binding.bannerImg.adapter = viewAdapter
            binding.bannerImg.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
            binding.bannerImg.currentItem = 0
        }


        fun update(item: PlaymateDetailItemData) {
            itemData = item
            binding.tvTitle.text = item.data.categoryName
            binding.tvSummary.text = item.data.summary

            val labelItems = item.data.labels.map {
                PlaymateDetailLabel(it)
            }
            if (labelItems.isNullOrEmpty()) {
                binding.rvLabel.gone()
            } else {
                binding.rvLabel.show()
                labelAdapter.submitList(labelItems)
            }

            val imageItems = item.data.images.map {
                PlaymateDetailImg(it)
            }
            if (imageItems.isNullOrEmpty()) {
                binding.bannerImg.gone()
            } else {
                binding.bannerImg.show()
                if (imageItems.size == 1) {
                    binding.bannerImg.updateLayoutParams<ConstraintLayout.LayoutParams> {
                        dimensionRatio = null
                        marginStart = 16.dp()
                        marginEnd = 16.dp()
                    }
                } else {
                    binding.bannerImg.updateLayoutParams<ConstraintLayout.LayoutParams> {
                        dimensionRatio = "320:192"
                        marginStart = 16.dp()
                        marginEnd = 0
                    }
                }
                viewAdapter.setItemList(imageItems)
            }
            if (item.data.voice.isEmpty()) {
                binding.vSound.gone()
            } else {
                binding.vSound.show()
                binding.vSound.setSoundUrl(item.data.voice)
            }
        }
    }

    internal inner class PreviewViewHolder(val binding: LayoutPlaymateDetailBannerItemBinding) :
        RecyclePagerAdapter.PagerViewHolder(binding.root)

    internal inner class ViewAdapter : RecyclePagerAdapter<PreviewViewHolder>() {

        private val itemList = mutableListOf<PlaymateDetailImg>()

        fun setItemList(list: List<PlaymateDetailImg>) {
            itemList.clear()
            itemList.addAll(list)
            notifyDataSetChanged()
        }

        override fun getItemViewType(position: Int): Int {
            return position
        }

        override fun getItemCount(): Int {
            return itemList.size
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PreviewViewHolder {
            val binding = LayoutPlaymateDetailBannerItemBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
            return PreviewViewHolder(binding)
        }

        override fun onBindViewHolder(holder: PreviewViewHolder, position: Int) {
            val itemData = itemList.getOrNull(position)
            holder.itemView.findViewById<NetworkImageView>(R.id.id_playmate_detail_photo)?.apply {
                setImageUrl(itemData?.url)
                onClick {
                    itemData?.let {
                        previewImage(holder.itemView.context.getActivity(), itemData, position)
                    }
                }
            }
        }

        private fun previewImage(context: BaseActivity?, img: PlaymateDetailImg, position: Int) {
            context ?: return
            val images = arrayListOf<String>()
            images.addAll(itemList.map { it.url })
            if (images.isEmpty()) {
                return
            }
            goImagePreviewActivity(
                context,
                images,
                position
            )
        }
    }


}