package com.adealink.weparty.ui.main

import android.annotation.SuppressLint
import android.graphics.Outline
import android.os.Bundle
import android.view.View
import android.view.ViewOutlineProvider
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.aab.util.getCompatDimension
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.startup.DistributedLoadManager
import com.adealink.weparty.AppModule
import com.adealink.weparty.R
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.recycleview.adapter.BaseTabFragmentStateAdapter
import com.adealink.weparty.commonui.widget.EmptyFragment
import com.adealink.weparty.constant.TAG_TIME_APP_START
import com.adealink.weparty.constant.logTime
import com.adealink.weparty.databinding.FragmentMainBinding
import com.adealink.weparty.databinding.LayoutMainTabBinding
import com.adealink.weparty.module.im.dot.messageDot
import com.adealink.weparty.ui.main.tab.ITabManager
import com.adealink.weparty.ui.main.tab.MAIN_TABS
import com.adealink.weparty.ui.main.tab.MESSAGE_TAB
import com.adealink.weparty.ui.main.tab.Tab
import com.adealink.weparty.ui.main.tab.TabManager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import java.util.LinkedList
import java.util.Queue

class MainFragment : BaseFragment(R.layout.fragment_main), ITabManager by TabManager() {

    companion object {
        const val TAG = "MainFragment"

        fun newInstance(mainTabKey: String?, subTabKey: String?): MainFragment {
            return MainFragment().apply {
                arguments = Bundle().apply {
                    putString(AppModule.Main.EXTRA_MAIN_TAB, mainTabKey)
                    putString(AppModule.Main.EXTRA_MAIN_SUB_TAB, subTabKey)
                }
            }
        }
    }

    private val binding by viewBinding(FragmentMainBinding::bind)
    private lateinit var dlManager: DistributedLoadManager
    private lateinit var mainPagerAdapter: MainPageAdapter

    @SuppressLint("MissingSuperCall")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        logTime(TAG_TIME_APP_START, "MainFragment.onViewCreated()")
        dlManager = DistributedLoadManager(lifecycle, stepsLoad())
        activity?.let { dlManager.triggerDistributedLoad(it) }
    }

    private fun stepsLoad(): Queue<Runnable> {
        val steps = LinkedList<Runnable>()
        steps.add(Runnable {
            Log.d(TAG, "MainFragment.step1: initViews, initComponents, observeViewModel")
            initViews()
            initComponents()
            observeViewModel()
        })
        steps.add(Runnable {
            Log.d(TAG, "MainFragment.step2: loadData")
            loadData()
        })
        return steps
    }

    override fun initViews() {
        super.initViews()
        initBlur()
        initTabs(MAIN_TABS)

        mainPagerAdapter = MainPageAdapter()
        binding.vpContent.offscreenPageLimit = 1
        binding.vpContent.adapter = mainPagerAdapter
        binding.vpContent.isSaveEnabled = false
        binding.vpContent.isUserInputEnabled = false
        (binding.vpContent.getChildAt(0) as? RecyclerView)?.setItemViewCacheSize(getCount())
        TabLayoutMediator(
            binding.tlTab,
            binding.vpContent,
            true,
             true
        ) { tabLayout, position ->
            tabLayout.setCustomView(R.layout.layout_main_tab)
            tabLayout.customView?.let { customView ->
                val tabBinding = LayoutMainTabBinding.bind(customView)
                val tab = getTab(position) ?: return@let
                onConfigureTab(tab, tabBinding)
                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?) {
            }

        })

        setDefaultTab(tabKey = arguments?.getString(AppModule.Main.EXTRA_MAIN_TAB))
    }

    private fun onConfigureTab(tab: Tab, binding: LayoutMainTabBinding) {
        when (tab) {
            MESSAGE_TAB -> {
                binding.vDot.observeDot(viewLifecycleOwner, messageDot)
            }
        }
    }

    private fun initBlur() {
        binding.blurBar.setClipToOutline(true)
        binding.blurBar.outlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View?, outline: Outline?) {
                outline ?: return
                binding.blurBar.background?.getOutline(outline)
                outline.alpha = 1f
            }
        }
//        val radius = 25f
//        val minBlurRadius = 4f
//        val step = 4f
        //set background, if your root layout doesn't have one
        val windowBackground = activity?.window?.decorView?.background
        binding.blurBar.setupWith(binding.blurTarget)
            .setFrameClearDrawable(windowBackground)
            .setBlurRadius(8f)

        binding.blurBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = getCompatDimension(R.dimen.main_bottom_bar_margin_bottom).toInt()
        }
    }

    fun updateTabView(
        tabView: TabLayout.Tab?,
        isSelected: Boolean,
        position: Int
    ) {
        val tab = getTab(position) ?: return
        tabView?.customView?.let {
            val customViewBinding = LayoutMainTabBinding.bind(it)
            if (isSelected) {
                customViewBinding.ivTabBg.setImageResource(tab.iconSelected)
            } else {
                customViewBinding.ivTabBg.setImageResource(tab.icon)
            }
        }
    }

    /**
     * adb shell am start -a android.intent.action.VIEW -d "jiehe://gami/main?tab=room&&subTab=XXXX"
     */
    fun setDefaultTab(tabKey: String? = "") {
        val tab = tabKey
        if (tab.isNullOrEmpty()) {
            return
        }
        val tabIndex = MAIN_TABS.indexOfFirst { it.type.tab == tab }
        if (tabIndex != -1) {
            binding.vpContent.setCurrentItem(tabIndex, false)
        }
    }

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

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

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

    }


}