package com.adealink.weparty.share.qrcode

import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.recycleview.adapter.BaseTabFragmentStateAdapter
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.commonui.widget.EmptyFragment
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.module.playmate.PlaymateModule
import com.adealink.weparty.module.playmate.data.UserPlaymateCategoryData
import com.adealink.weparty.module.share.Share
import com.adealink.weparty.share.R
import com.adealink.weparty.share.databinding.DialogQrCodeShareBinding
import com.adealink.weparty.share.databinding.LayoutQrCodeTabItemBinding
import com.adealink.weparty.share.qrcode.viewmodel.QRCodeViewModel
import com.adealink.weparty.share.viewmodel.ShareViewModelFactory
import com.adealink.weparty.ui.main.tab.ITabManager
import com.adealink.weparty.ui.main.tab.TabManager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.adealink.weparty.R as APP_R

@RouterUri(path = [Share.QRCodeShare.PATH], desc = "二维码分享")
class QRCodeShareDialog : BottomDialogFragment(R.layout.dialog_qr_code_share),
    ITabManager by TabManager() {

    private val binding by viewBinding(DialogQrCodeShareBinding::bind)

    private val playmateViewModel by fastLazy { PlaymateModule.getPlaymateViewModel(this) }
    private val qrCodeViewModel by viewModels<QRCodeViewModel> { ShareViewModelFactory() }
    private lateinit var pagerAdapter: ShareOtherPageAdapter

    private val myCategoryList = mutableListOf<UserPlaymateCategoryData>()

    override fun initViews() {
        super.initViews()
        binding.clTop.onClick {
            showCategoryChooseDialog()
        }

        pagerAdapter = ShareOtherPageAdapter()
        binding.vpContent.offscreenPageLimit = 1
        binding.vpContent.adapter = pagerAdapter
        binding.vpContent.isSaveEnabled = false
        TabLayoutMediator(
            binding.tlTab,
            binding.vpContent,
            true,
            true
        ) { tabLayout, position ->
            tabLayout.setCustomView(R.layout.layout_qr_code_tab_item)
            tabLayout.customView?.let { customView ->
                updateTabView(
                    tabLayout,
                    0 == position,
                    position
                )
            }
        }.attach()
        binding.tlTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {
                updateTabView(tab, true, tab?.position ?: 0)
            }

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

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

        })
        binding.vpContent.currentItem = 0
    }

    fun updateTabView(
        tabView: TabLayout.Tab?,
        isSelected: Boolean,
        position: Int
    ) {
        tabView?.customView?.let {
            val customViewBinding = LayoutQrCodeTabItemBinding.bind(it)
            customViewBinding.tvTab.text = QR_CODE_TABS.getOrNull(position)?.name?.invoke() ?: ""
            if (isSelected) {
                customViewBinding.root.setBackgroundResource(APP_R.drawable.common_tab_item_bg)
                customViewBinding.tvTab.setTextColor(getCompatColor(APP_R.color.color_FF1D2129))
            } else {
                customViewBinding.root.setBackgroundResource(0)
                customViewBinding.tvTab.setTextColor(getCompatColor(APP_R.color.color_FF4E5969))
            }
        }
    }

    override fun loadData() {
        super.loadData()
        playmateViewModel?.getUserPlaymateCategory(AccountModule.uid, true)
            ?.observe(viewLifecycleOwner) { rlt ->
                when (rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(rlt)
                    }

                    is Rlt.Success<List<UserPlaymateCategoryData>> -> {
                        updateMyCategory(rlt.data)
                    }
                }
            }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        qrCodeViewModel.currentCategoryLD.observe(viewLifecycleOwner) {
            selectCategory(it)
        }
    }

    private fun updateMyCategory(list: List<UserPlaymateCategoryData>) {
        myCategoryList.clear()
        myCategoryList.addAll(list)
        qrCodeViewModel.selectCategory(list.firstOrNull())
    }

    private fun selectCategory(category: UserPlaymateCategoryData?) {
        //更新视图
        binding.ivCategory.setImageUrl(category?.icon)
        binding.tvCategory.text = category?.name

    }

    private fun showCategoryChooseDialog() {
        ChooseCategoryDialog().apply {
            setCategoryList(myCategoryList, qrCodeViewModel.currentCategoryLD.value)
            show(this@QRCodeShareDialog.childFragmentManager, "ChooseCategoryDialog")
        }
    }

    internal inner class ShareOtherPageAdapter : BaseTabFragmentStateAdapter(this) {
        override fun getTabName(pos: Int): String {
            return ""
        }

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

        override fun createFragment(position: Int): Fragment {
            val homeTab = QR_CODE_TABS.getOrNull(position) ?: return EmptyFragment()
            return homeTab.fragmentBuilder.invoke()
        }

    }
}