package com.seatel.mobilehall.ui.home.adapter

import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.size
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import coil.load
import com.bumptech.glide.Glide
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ItemBinding
import com.seatel.mobilehall.ui.home.model.BannersModel
import com.seatel.mobilehall.ui.login.activity.TermsAndConditionsActivity

class ImageSliderAdapter(
    private val banners: List<BannersModel>,
    private var onActionLink: (String) -> Unit,
) : RecyclerView.Adapter<ImageSliderAdapter.SliderVH>() {

    private val newList: List<BannersModel> =
        listOf(banners.last()) + banners + listOf(banners.first())

    class SliderVH(val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root)

    lateinit var binding: ItemBinding
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ImageSliderAdapter.SliderVH {
        val binding = ItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SliderVH(binding)
    }

    override fun onBindViewHolder(holder: ImageSliderAdapter.SliderVH, position: Int) {
        val banner = newList[position]
        Glide.with(holder.itemView.context).load(banner.imageUrl).into(holder.binding.imageView)
        holder.itemView.setOnClickListener(View.OnClickListener {
            when (banner.actionType) {
                "in-app" -> {
                    TermsAndConditionsActivity.launch(
                        holder.itemView.context, banner.imageUrl!!
                    )
                }
                "out-app" -> {
                    banner.url?.let { url ->
                        onActionLink.invoke(url)
                    }
                }
            }
        })
    }

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