package com.gamedog.vididin.main.fragments

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import androidx.core.view.isVisible
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.highlightpro.HighlightPro
import com.ama.core.architecture.highlightpro.parameter.Constraints
import com.ama.core.architecture.highlightpro.parameter.HighlightParameter
import com.ama.core.architecture.highlightpro.parameter.MarginOffset
import com.ama.core.architecture.highlightpro.shape.OvalShape
import com.ama.core.architecture.util.ResUtil
import com.ama.core.architecture.util.ResUtil.dp
import com.ama.core.architecture.util.setStatusBarDarkFont
import com.ama.core.common.widget.PopMenuView
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.beans.RECORD_GOLD_PLUS_WATCH_VIDEO_BY_TIME_DURATION
import com.gamedog.vididin.beans.RecordGold
import com.gamedog.vididin.core.login.login.AccountManager
import com.gamedog.vididin.main.WatchAdDialog
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.manager.GuideManager
import com.gamedog.vididin.manager.TaskManager
import com.gamedog.vididin.router.Router
import com.gamedog.vididin.youtubestatistic.RewardConst
import com.gamedog.vididin.youtubestatistic.RewardConst.Companion.Check_Interval_MS
import com.remax.bill.ads.AdResult
import com.remax.bill.ads.ext.AdShowExt
import com.viddin.videos.free.R
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.getValue
import com.viddin.videos.free.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 mWatchedVideoTotal = 0
    private var mSwipedVideoTotal = 0
    private var mLastShowedRewardedAd = true


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

    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


        popMenu.setMenuList(
            mutableListOf(
                PopMenuView.MenuItem(R.mipmap.home_menu_1, 0, 0) {
                    Router.Benefit.startActivity(requireActivity())
                    StatisticUtil.reportEvents(StatisticUtil.KEY_Chest_Claim_Click)
                },
                PopMenuView.MenuItem(R.mipmap.home_menu_2,R.mipmap.icon_gold_ss_new, 0) {
                    WatchAdDialog(requireActivity(), VidiConst.WATCH_AD_FOR_DAILY_EARN_GOLD, WatchAdDialog.FROM_HOME_MENU,null).show()
                },
                PopMenuView.MenuItem(R.mipmap.home_menu_3,0, 0) {
                    Router.Game.startActivity(requireActivity())
                },
                PopMenuView.MenuItem(R.mipmap.home_menu_4,0, 0) {
                    Router.ZeroBuy.startActivity(requireActivity())
                }
            ))

        updatePopMenuTexts()

        registerEvents({ data->
            when (data?.mEventType) {
                VididinEvents.Event_HOME_WATCH_Time_TICK -> {
                    handleWatchTimeTick()
                }

                VididinEvents.Event_Finish_One_Video -> {
                    handleEventOneVideoWatched()
                }

                VididinEvents.EVENT_BOX_TASK_STATE_CHANGED -> {
                    updatePopMenuTexts()
                }
            }

        }, VididinEvents.Event_HOME_WATCH_Time_TICK, VididinEvents.Event_Finish_One_Video, VididinEvents.EVENT_BOX_TASK_STATE_CHANGED)

    }

    private fun updatePopMenuTexts() {
        for (index in 0..3) {
            var textStr = ""
            when (index) {
                3 -> {
                    textStr = TaskManager.instance().boxTaskStatus().getLeftValidBoxTotalDurationStr()
                }

                2 -> {
                    textStr = VidiConst.WATCH_AD_REWARD_GOLD.toString()
                }

                1 -> {
                    textStr = ResUtil.getString(R.string.game_discord)
                }

                0 -> {
                    textStr = ResUtil.getString(R.string.zero_buy_tag)
                }
            }

            binding?.popMenu?.setMenuText(index, textStr)
        }
    }


    private fun showGuide() {
        HighlightPro.with(this@HomeFragment)
            .setHighlightParameter {
                HighlightParameter.Builder()
                    .setHighlightView(binding?.popMenu!!, {
                    })
                    .setTipsViewId(R.layout.guide_step_popmnue)
                    .setHighlightShape(OvalShape(binding?.popMenu?.measuredWidth!!.toFloat()/2))
                    .setHighlightHorizontalPadding(0.dp)
                    .setConstraints(Constraints.TopToBottomOfHighlight + Constraints.EndToEndOfHighlight)
                    .setMarginOffset(MarginOffset(top = -20.dp.toInt(), end = 20.dp.toInt()))
                    .build()
            }
            .setBackgroundColor("#cc000000".toColorInt())
            .setOnShowCallback { index ->

            }
            .setOnDismissCallback {
                saveGuideState()
                binding?.popMenu!!.toggleMenu()
            }
            .interceptBackPressed(true)
            .show()

        StatisticUtil.reportEvents(StatisticUtil.KEY_Guide, mapOf("Guide" to 5))
    }

    private fun saveGuideState() {
        GuideManager.instance().setGuideIndex(VidiConst.GUIDE_INDEX_POP_MENU)
    }

    private fun handleEventOneVideoWatched() {
        mWatchedVideoTotal++

        if (mWatchedVideoTotal % VIDEO_NUM_GAP_FOR_AD_WATCHED == 0) {
            if (mLastShowedRewardedAd) {
                showInterstitialAd {}
            } else {
                handleShouldShowAdDialog()
            }

            // reset state
            mLastShowedRewardedAd = !mLastShowedRewardedAd
            mWatchedVideoTotal = 0
            mSwipedVideoTotal = 0
        }
    }

    private fun handleEventOneVideoSwiped() {
        mSwipedVideoTotal ++

        if (mSwipedVideoTotal % VIDEO_NUM_GAP_FOR_AD_SWIPED == 0) {
            if (mLastShowedRewardedAd) {
                showInterstitialAd {}
            } else {
                handleShouldShowAdDialog()
            }

            // reset state
            mLastShowedRewardedAd = !mLastShowedRewardedAd
            mWatchedVideoTotal = 0
            mSwipedVideoTotal = 0
        }
    }

    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)
            val goldNum = RewardConst.HOME_WATCH_REWARD_NUM.toLong()
            AccountManager.adjustGold(goldNum, RecordGold(RECORD_GOLD_PLUS_WATCH_VIDEO_BY_TIME_DURATION, goldNum))
            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()

                    handleEventOneVideoSwiped()
                }

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

            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)


        //viewPager2.offscreenPageLimit = 3
    }

    override fun ViewBinding.initObservers() {

    }

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

    override fun onResume() {
        super.onResume()
        setStatusBarDarkFont(isDarkFont = isStatusBarDarkFont)

        if (!mHasShowGuide) {
            val guideStateValue = GuideManager.instance().getCurGuideIndex()
            if (binding?.popMenu?.isVisible == true && guideStateValue == VidiConst.GUIDE_INDEX_ZERO) {
                binding?.popMenu?.postDelayed({
                    showGuide()
                    mHasShowGuide = true
                }, 5)
            }
        }
    }

    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 showInterstitialAd(callback: () -> Unit) {
        lifecycleScope.launch {
            try {
                when (val result = AdShowExt.showInterstitialAd(requireActivity())) {
                    is AdResult.Success -> {
                        callback.invoke()
                    }

                    is AdResult.Failure -> {
                        callback.invoke()
                    }

                    AdResult.Loading -> {
                    }
                }

            } catch (e: Exception) {
                callback.invoke()
            }
        }
    }

    private fun handleShouldShowAdDialog() {
        val adDialog = WatchAdDialog(requireActivity(), VidiConst.WATCH_AD_FOR_DAILY_WATCH_AD,
            WatchAdDialog.FROM_WATCH_5VIDEOS,null)
        adDialog.setOnCloseListener {
            showInterstitialAd {}
        }
        adDialog.show()
    }

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

    companion object {
        const val VIDEO_NUM_GAP_FOR_AD_WATCHED = 3
        const val VIDEO_NUM_GAP_FOR_AD_SWIPED = 5

        internal fun newInstance() = HomeFragment()
    }

}