package com.adealink.weparty.commonui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.viewpager2.widget.ViewPager2
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.util.DisplayUtil
import com.adealink.weparty.R
import com.adealink.weparty.commonui.drawabletoolbox.DrawableBuilder
import com.adealink.weparty.databinding.LayoutDotTabBinding
import com.adealink.weparty.databinding.LayoutDotTabItemBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class DotTabLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : ConstraintLayout(context, attrs, defStyleAttr) {
    var binding: LayoutDotTabBinding =
        LayoutDotTabBinding.inflate(LayoutInflater.from(getContext()), this, true)
    private var viewPager2: ViewPager2? = null
    var tabLayout = binding.dotTabLayout

    fun createMediatorAndAttach(
        viewPager2: ViewPager2?,
        currentItem: Int,
    ) {
        this.viewPager2 = viewPager2
        viewPager2?.let {
            TabLayoutMediator(
                tabLayout, it, true, false
            ) { tab: TabLayout.Tab, position: Int ->
                run {
                    tab.setCustomView(R.layout.layout_dot_tab_item)
                    updateTabView(
                        tab,
                        currentItem == position)
                }
            }.attach()
        }
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                updateTabView(tab, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                updateTabView(tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }

    val dotSelectedBg = DrawableBuilder().rectangle()
        .rounded()
        .solidColor(getCompatColor(R.color.dot_tab_select_color))
        .size(DisplayUtil.dp2px(6f)).build()

    val dotUnSelectedBg = DrawableBuilder().rectangle()
        .rounded()
        .solidColor(getCompatColor(R.color.dot_tab_unselect_color))
        .size(DisplayUtil.dp2px(6f)).build()

    fun updateTabView(
        tab: TabLayout.Tab?,
        isSelected: Boolean,
    ) {
        tab?.customView?.let {
            when {
                isSelected -> {
                    val binding = LayoutDotTabItemBinding.bind(it)
                    binding.dot.background = dotSelectedBg
                }
                else -> {
                    val binding = LayoutDotTabItemBinding.bind(it)
                    binding.dot.background = dotUnSelectedBg
                }
            }
        }
    }
}