package com.gamedog.vididin.main.fragments

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.ama.core.architecture.appBase.AppViewsFragment
import com.ama.core.architecture.appBase.OnFragmentBackgroundListener
import com.ama.core.architecture.util.setStatusBarDarkFont
import com.ama.core.common.util.asSafe
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.core.login.login.AccountManager
import com.gamedog.vididin.main.fragments.home.HomeFragmentStateAdapter
import com.gamedog.vididin.main.fragments.home.fragment.HomeItemFragment
import com.gamedog.vididin.main.interfaces.OnSwitchTabListener
import com.gamedog.vididin.main.interfaces.OnTabStyleListener
import com.gamedog.vididin.youtubestatistic.RewardConst
import com.gamedog.vididin.youtubestatistic.RewardConst.Companion.Check_Interval_MS
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.getValue
import com.gamedog.vididin.databinding.VididinappFeatureHomeFragmentHomeBinding as ViewBinding
import com.gamedog.vididin.main.fragments.home.YoutubeViewModel as ViewModel
import com.gamedog.vididin.main.fragments.home.YoutubeUiState as UiState



@AndroidEntryPoint
class HomeFragment : AppViewsFragment<ViewBinding, UiState, ViewModel>(), OnSwitchTabListener, OnFragmentBackgroundListener {

    private var mTotalMs: Long = 0L
    override val mViewModel: ViewModel by viewModels()
    override var isBackgroundBright: Boolean = true

    private val mViewPagerAdapter by lazy { HomeFragmentStateAdapter(this) }

    override fun inflateViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ) = ViewBinding.inflate(inflater, container, false)

    override fun ViewBinding.initWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(viewPager2) { v, insets ->
            val systemBars =
                insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())
            v.updatePadding(top = systemBars.top)
            insets
        }
    }

    override fun ViewBinding.initViews() {
        viewPager2.setPageTransformer { _, _ -> }
        viewPager2.offscreenPageLimit = 1
        viewPager2.adapter = mViewPagerAdapter

        registerEvents({
            handleWatchTimeTick()
        }, VididinEvents.Event_HOME_WATCH_Time_TICK,)
    }

    private fun handleWatchTimeTick() {
        mTotalMs += Check_Interval_MS

        if (mTotalMs < RewardConst.HOME_WATCH_DURATION) {
            binding?.dragIconView?.setProgress(mTotalMs * 100/RewardConst.HOME_WATCH_DURATION)
        } else {
            mTotalMs = 0L
            binding?.dragIconView?.setProgress(mTotalMs * 100/ RewardConst.HOME_WATCH_DURATION)
            AccountManager.addGold(RewardConst.HOME_WATCH_REWARD_NUM)
            binding?.dragIconView?.showRewardGoldAnim()
        }
    }

    override fun ViewBinding.initListeners() {
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val fragment = mViewPagerAdapter.getFragmentByIndex(position)
                if (fragment != null) {
                    setHomeTabStyle(fragment)
                    val curFragment: HomeItemFragment = fragment as HomeItemFragment
                    curFragment.loadVideo()
                }

                // load more
                if (mViewPagerAdapter.itemCount > 0 && position == mViewPagerAdapter.itemCount - 2) {
                    lifecycleScope.launch {
                        mViewModel.loadVideoPage()
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
            }
        })

        childFragmentManager.registerFragmentLifecycleCallbacks(object :
            FragmentLifecycleCallbacks() {
            override fun onFragmentResumed(fm: FragmentManager, fra: Fragment) {
                super.onFragmentResumed(fm, fra)
                setHomeTabStyle(fra)
            }
        }, false)
    }

    override fun ViewBinding.initObservers() {

    }

    override fun ViewBinding.onUiStateCollect(uiState: UiState) {
        mViewPagerAdapter.submitList(uiState.playLists)
    }

    override fun onResume() {
        super.onResume()
        setStatusBarDarkFont(isDarkFont = isBackgroundBright)
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onSwitchTab(index: Int, smoothScroll: Boolean) {
        var item = index
        if (index < 0 || index >= mViewPagerAdapter.itemCount) {
            item = mViewPagerAdapter.itemCount - 1
        }
        binding?.viewPager2?.setCurrentItem(item, smoothScroll)
    }



    private fun setHomeTabStyle(f: Fragment?) {
        isBackgroundBright = f.asSafe<OnFragmentBackgroundListener>()?.isBackgroundBright ?: return
        activity.asSafe<OnTabStyleListener>()?.onTabIsDarkFont(isBackgroundBright)
    }

    companion object {
        internal fun newInstance() = HomeFragment()
    }

}