package kr.co.vividnext.sodalive.audio_content.box

import android.widget.LinearLayout
import com.google.android.material.tabs.TabLayout
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.audio_content.order.AudioContentOrderListFragment
import kr.co.vividnext.sodalive.audio_content.playlist.AudioContentPlaylistListFragment
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.databinding.ActivityAudioContentBoxBinding

class AudioContentBoxActivity : BaseActivity<ActivityAudioContentBoxBinding>(
    ActivityAudioContentBoxBinding::inflate
) {
    override fun setupView() {
        setupToolbar()
        setupTabs()

        supportFragmentManager.beginTransaction()
            .replace(R.id.fl_container, AudioContentOrderListFragment())
            .commit()
    }

    private fun setupToolbar() {
        binding.toolbar.tvBack.text = "내 보관함"
        binding.toolbar.tvBack.setOnClickListener { finish() }
    }

    private fun setupTabs() {
        val tabs = binding.tabs
        tabs.addTab(tabs.newTab().setText("구매목록"))
        tabs.addTab(tabs.newTab().setText("재생목록"))

        tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                tab.view.isSelected = true

                when (tab.position) {
                    1 -> supportFragmentManager.beginTransaction()
                        .replace(R.id.fl_container, AudioContentPlaylistListFragment())
                        .commit()

                    else -> supportFragmentManager.beginTransaction()
                        .replace(R.id.fl_container, AudioContentOrderListFragment())
                        .commit()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                tab.view.isSelected = false
            }

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

        val tabStrip = tabs.getChildAt(0) as LinearLayout
        for (i in 0 until tabStrip.childCount) {
            val tab = tabStrip.getChildAt(i)
            val params = tab.layoutParams as LinearLayout.LayoutParams
            params.setMargins(12, 0, 12, 0)
            params.height = LinearLayout.LayoutParams.WRAP_CONTENT
            tab.layoutParams = params
            tab.minimumHeight = 0
        }
    }
}
