package com.gamedog.vididin.main.fragments

import android.Manifest
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.graphics.toColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.ama.core.architecture.appBase.AppViewsFragment
import com.ama.core.architecture.appBase.OnFragmentBackgroundListener
import com.ama.core.architecture.util.AndroidUtil
import com.ama.core.architecture.util.ResUtil
import com.ama.core.architecture.util.ResUtil.dp
import com.ama.core.architecture.util.eventbus.NotifyMan
import com.ama.core.architecture.util.permission.PermissionUtil
import com.ama.core.architecture.util.setOnClickBatch
import com.ama.core.architecture.util.setStatusBarDarkFont
import com.viddin.videos.free.R
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.core.login.login.AccountManager
import com.gamedog.vididin.main.MainActivity
import com.gamedog.vididin.main.WatchAdDialog
import com.gamedog.vididin.main.fragments.task.DailySignDialog
import com.gamedog.vididin.main.fragments.task.DailySignSuccessDialog
import com.gamedog.vididin.main.fragments.task.TaskBean
import com.gamedog.vididin.main.fragments.task.widget.DailyTaskItemView
import com.gamedog.vididin.main.interfaces.OnTabClickAgainListener
import com.gamedog.vididin.manager.TaskManager
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_FINISH
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_ONGOING
import com.gamedog.vididin.router.Router
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.highlightpro.shape.RectShape
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.manager.GuideManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.launch
import kotlin.getValue
import com.viddin.videos.free.databinding.VididinappFeatureMessageFragmentMessageBinding as ViewBinding
import com.gamedog.vididin.main.fragments.home.YoutubeViewModel as ViewModel
import com.gamedog.vididin.main.fragments.home.YoutubeUiState as UiState



@AndroidEntryPoint
class TasksFragment : AppViewsFragment<ViewBinding, UiState, ViewModel>(), OnTabClickAgainListener, OnFragmentBackgroundListener {


    private var mTaskConfig: TaskBean? = null
    override val mViewModel: ViewModel by viewModels()
    override var isBackgroundBright: Boolean = true
    private var isStatusBarDarkFont = false

    private val mDailyWatchVideoViewList = mutableListOf<DailyTaskItemView>()
    private val mDailyWatchAdViewList = mutableListOf<DailyTaskItemView>()


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

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

        //setImmerseRootView(scrollView)
    }




    override fun ViewBinding.initViews() {
        with(binding) {
            setOnClickBatch(llSignRoot, llTaskBenefit, llTaskWatchAd, llTaskGame,
                llTaskZerobuy, flConvertGold2Cash, tvWithdraw) {
                when(this) {
                    llSignRoot->{
                        if (!TaskManager.instance().dailySignStatus().isDailySignAllOperationDone()) {
                            DailySignDialog(requireActivity()).show()
                        }
                    }

                    llTaskBenefit->{
                        Router.Benefit.startActivity(requireActivity())
                        StatisticUtil.reportEvents(StatisticUtil.KEY_Chest_Claim_Click)
                    }

                    llTaskWatchAd->{
                        WatchAdDialog(requireActivity(), VidiConst.WATCH_AD_FOR_DAILY_EARN_GOLD, WatchAdDialog.FROM_TASK_FRAGMENT_ICON, 200).show()
                    }

                    llTaskGame->{
                        Router.Game.startActivity(requireActivity())

                        StatisticUtil.reportEvents(StatisticUtil.KEY_H5_Button_Click)
                    }

                    llTaskZerobuy->{
                        gotoZeroBuy()
                    }

                    flConvertGold2Cash->{
                        WatchAdDialog(requireActivity(), VidiConst.WATCH_AD_FOR_CONVERT_GOLD_2_CASH, WatchAdDialog.FROM_CONVERT_GOLD_TO_CASH, null).show()
                    }

                    tvWithdraw->{
                        Router.Withdraw.startActivity(requireActivity())

                        StatisticUtil.reportEvents(StatisticUtil.KEY_Withdraw_Click)
                    }
                }
            }



            with(beginnerTaskWithdraw) {
                initUI(R.mipmap.icon_cash_s, R.string.beginner_withdraw_title, R.string.resgatar)
                //setRewardTextStyle(21, R.color.green_39)
                updateNewBieFirstWithdrawUI()
            }


            with(beginnerTaskDiscord) {
                initUI(R.mipmap.icon_dicord, R.string.beginner_discord_title,R.string.resgatar)
                updateNewBieDiscordUI()
            }

            with(beginnerTaskEnableNotify) {
                initUI(R.mipmap.icon_notify, R.string.beginner_notify_title,R.string.Resgatado)
                updateNewBieNotifyUI()
            }


            addDailySubTasks()

            updateUIGoldTotal()
            updateUICashTotal()
            updateDailyWatchVideoUI()
            updateDailyWatchAdUI()
            update4TaskTextInfo()
        }

        lifecycleScope.launch {
            mTaskConfig = TaskManager.instance().getTaskConfig()
        }

        if (GuideManager.instance().getCurGuideIndex() == VidiConst.GUIDE_INDEX_GIFT) {
            llTaskGame.postDelayed({
                ivAdIndi.isVisible = false
                showGuide1()
            }, 5)
        }

        updateDailySignButUI()
    }

    private fun gotoZeroBuy() {
        Router.ZeroBuy.startActivity(requireActivity())
        StatisticUtil.reportEvents(StatisticUtil.KEY_lottery_Button_Click)
    }

    private fun addDailySubTasks() {
        //1. 阶梯广告
        val dailyWatchAdTask = TaskManager.instance().getDailyAdTask()
        if (dailyWatchAdTask != null && dailyWatchAdTask.status == "active"
            && dailyWatchAdTask.reward_details.isNotEmpty()) {

            dailyWatchAdTask.reward_details.forEachIndexed { index, detail ->
                val watchTaskItemView = DailyTaskItemView(requireActivity())
                watchTaskItemView.setActionFun {
                    handleDailyAdButClicked(index)
                }
                mDailyWatchAdViewList.add(watchTaskItemView)

                binding?.dailyTasksContainer!!.run {
                    watchTaskItemView.initUI(R.mipmap.icon_ad, R.string.daily_ad_task_title,
                        detail.target_count, detail.value)

                    addView(watchTaskItemView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                    if (true) {
                        val separateLine = View(requireActivity())
                        separateLine.setBackgroundResource(R.color.gray_f2)
                        addView(separateLine, LinearLayout.LayoutParams.MATCH_PARENT, ResUtil.getPixelSize(R.dimen.dp1))
                    }
                }
            }
        }

        //2. 阶梯视频
        val dailyWatchVideoTask = TaskManager.instance().getDailyVideoTask()
        if (dailyWatchVideoTask != null && dailyWatchVideoTask.status == "active"
            && dailyWatchVideoTask.reward_details.isNotEmpty()) {

            dailyWatchVideoTask.reward_details.forEachIndexed {index, detail ->
                val watchTaskItemView = DailyTaskItemView(requireActivity())
                watchTaskItemView.setActionFun {
                    handleDailyVideoButClicked(index)
                }
                mDailyWatchVideoViewList.add(watchTaskItemView)

                binding?.dailyTasksContainer!!.run {
                    watchTaskItemView.initUI(R.mipmap.icon_video_task, R.string.daily_video_task_title,
                        detail.target_count, detail.value)

                    addView(watchTaskItemView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                    if (index != dailyWatchVideoTask.reward_details.size - 1) {
                        val separateLine = View(requireActivity())
                        separateLine.setBackgroundResource(R.color.gray_f2)
                        addView(separateLine, LinearLayout.LayoutParams.MATCH_PARENT, ResUtil.getPixelSize(R.dimen.dp1))
                    }
                }
            }
        }
    }

    private fun updateUICashTotal() {
        binding?.tvCashTotal?.text = buildString {
            append(ResUtil.getString(R.string.cash))
            append(" ")
            append(String.format("%.2f", AccountManager.getCash()))
        }
    }

    private fun updateDailyWatchVideoUI() {
        val statusBean = TaskManager.instance().dailyWatchVideoStatus().getStatusBean()
        val subTaskStatusList = statusBean.getSubTaskRewardState()
        mDailyWatchVideoViewList.forEachIndexed { index, view ->
            view.updateProgress(statusBean.getTodayWatchedCount(), subTaskStatusList[index].state)
        }
    }

    private fun updateDailyWatchAdUI() {
        val statusBean = TaskManager.instance().dailyWatchAdStatus().getStatusBean()
        val subTaskStatusList = statusBean.getSubTaskRewardState()
        mDailyWatchAdViewList.forEachIndexed { index, view ->
            view.updateProgress(statusBean.getTodayWatchedCount(), subTaskStatusList[index].state)
        }
    }

    private fun update4TaskTextInfo() {
        with(binding!!) {
            tvBoxTaskState.text = TaskManager.instance().boxTaskStatus().getLeftValidBoxTotalDurationStr()
            tvAdWatchRewardNum.text = VidiConst.WATCH_AD_REWARD_GOLD.toString()
            tvGameTaskState.text = ResUtil.getString(R.string.game_discord)
            tvZeroBuyState.text = ResUtil.getString(R.string.zero_buy_tag)
        }
    }

    private fun updateUIGoldTotal() {
        binding?.tvGoldTotal?.text = AccountManager.getGold().toString()
    }

    override fun ViewBinding.initListeners() {
        registerEvents({data: NotifyMan.NotifyData<*>? ->
            when (data?.mEventType) {
                VididinEvents.Event_Sign_State_Changed -> {
                    updateDailySignButUI()
                }

                VididinEvents.Event_Account_Gold_Changed -> {
                    updateUIGoldTotal()
                }

                VididinEvents.Event_Account_Cash_Changed -> {
                    updateUICashTotal()
                }

                VididinEvents.EVENT_DAILY_WATCHED_VIDEO_NUM_CHANGED -> {
                    updateDailyWatchVideoUI()
                }

                VididinEvents.EVENT_DAILY_WATCHED_AD_NUM_CHANGED -> {
                    updateDailyWatchAdUI()
                }

                VididinEvents.EVENT_JUMP_2_FIRST_WITHDRAW -> {
                    binding?.newbieContainer?.postDelayed(object : Runnable {
                        override fun run() {
                            scroll2FirstWithdraw()
                        }
                    },1000)
                }

                VididinEvents.EVENT_NEWBIE_DISCORD_TASK_CHANGED -> {
                    updateNewBieDiscordUI()
                }

                VididinEvents.EVENT_NEWBIE_NOTIFY_TASK_CHANGED -> {
                    updateNewBieNotifyUI()
                }

                VididinEvents.EVENT_NEWBIE_FIRST_WITHDRAW_TASK_CHANGED -> {
                    updateNewBieFirstWithdrawUI()
                }

                VididinEvents.EVENT_BOX_TASK_STATE_CHANGED -> {
                    update4TaskTextInfo()
                }
            }
        }, VididinEvents.Event_Sign_State_Changed, VididinEvents.Event_Account_Cash_Changed,
            VididinEvents.Event_Account_Gold_Changed, VididinEvents.EVENT_DAILY_WATCHED_VIDEO_NUM_CHANGED,
            VididinEvents.EVENT_DAILY_WATCHED_AD_NUM_CHANGED, VididinEvents.EVENT_JUMP_2_FIRST_WITHDRAW,
            VididinEvents.EVENT_NEWBIE_DISCORD_TASK_CHANGED, VididinEvents.EVENT_NEWBIE_NOTIFY_TASK_CHANGED,
            VididinEvents.EVENT_NEWBIE_FIRST_WITHDRAW_TASK_CHANGED, VididinEvents.EVENT_BOX_TASK_STATE_CHANGED)
    }


    private fun scroll2FirstWithdraw() {
        binding?.newbieContainer?.let { binding?.scrollView?.scroll2ChildView(it) }
    }

    private fun updateDailySignButUI() {
        val hasFinishAllSignWork = TaskManager.instance().dailySignStatus().isDailySignAllOperationDone()

        binding?.ivGotoDailySign?.apply {
            setText(
                if (hasFinishAllSignWork) R.string.daily_sign_but_text_3 else R.string.daily_sign_but_text_1
            )
            isClickable = !hasFinishAllSignWork

            if (hasFinishAllSignWork) {
                background.setTint(ResUtil.getColor(R.color.gray_84))
            }
        }
    }

    private fun updateNewBieFirstWithdrawUI() {
        with(binding?.beginnerTaskWithdraw!!) {
            val stateBean = TaskManager.instance().newbieFirstWithdrawStatus().getStatusBean()
            setActionFun {
                if (stateBean.hasWithdrawed && !stateBean.hasClaimReward) {
                    TaskManager.instance().newbieFirstWithdrawStatus().claimReward()
                } else {
                    gotoWithDraw()
                }
            }

            setTaskStateInfo(
                stateBean.rewardGoldNum.toString(),
                if (stateBean.hasClaimReward) R.string.finished else R.string.go_and_do,
                ResUtil.getString(R.string.beginner_withdraw_desc),
                stateBean.hasClaimReward
            )
        }
    }

    private fun updateNewBieDiscordUI() {
        with(binding?.beginnerTaskDiscord!!) {
            val stateBean = TaskManager.instance().newbieJoinDiscordStatus().getStatusBean()
            val hasClaimDiscordGold = stateBean.hasClaimReward
            setActionFun {
                if (!hasClaimDiscordGold) {
                    gotoDiscord()
                    postDelayed({
                        if (TaskManager.instance().newbieJoinDiscordStatus().claimReward()) {
                            DailySignSuccessDialog(requireActivity()).initData(stateBean.rewardGoldNum, false).show()
                            updateNewBieDiscordUI()
                        }
                    }, 5000)
                }
            }

            setTaskStateInfo(
                stateBean.rewardGoldNum.toString(),
                if (stateBean.hasClaimReward) R.string.finished else R.string.go_and_do,
                String.format(ResUtil.getString(R.string.beginner_discord_desc), stateBean.rewardGoldNum),
                stateBean.hasClaimReward
            )
        }
    }

    private fun updateNewBieNotifyUI() {
        with(binding?.beginnerTaskEnableNotify!!) {
            setActionFun {
                val stateBean = TaskManager.instance().newbieEnableNotifyStatus().getStatusBean()
                val isNotifyEnable = AndroidUtil.isNotificationEnabled()
                if (!stateBean.hasClaimReward) {
                    if (!isNotifyEnable) {
                        gotoNotification()
                    } else {
                        TaskManager.instance().newbieEnableNotifyStatus().claimReward()
                        DailySignSuccessDialog(requireActivity()).initData(stateBean.rewardGoldNum, false).show()
                    }
                }
            }

            val stateBean = TaskManager.instance().newbieEnableNotifyStatus().getStatusBean()
            val isNotifyEnable = AndroidUtil.isNotificationEnabled()
            val actionButRes = if (stateBean.hasClaimReward) R.string.Resgatado else (if (isNotifyEnable) R.string.resgatar else R.string.go_and_do)
            setTaskStateInfo(stateBean.rewardGoldNum.toString(), actionButRes,
                String.format(ResUtil.getString(R.string.beginner_notify_desc), stateBean.rewardGoldNum), stateBean.hasClaimReward)
        }
    }



    override fun ViewBinding.initObservers() {
    }

    override fun ViewBinding.onUiStateCollect(uiState: UiState) {

    }

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

        val guideIndex = GuideManager.instance().getCurGuideIndex()
        if (guideIndex == VidiConst.GUIDE_INDEX_WITHDRAW) {
            showGuide2()
        }
    }

    override fun onTabClickAgain() {
    }

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

    private fun gotoWithDraw() {
        Router.Withdraw.startActivity(requireActivity())
    }

    private fun gotoDiscord() {
        AndroidUtil.openUrl(VidiConst.URL_DISCORD)
    }

    private fun gotoNotification() {
        PermissionUtil.checkPermission(Manifest.permission.POST_NOTIFICATIONS, object : PermissionUtil.ICallback() {
            override fun onAllGranted() {
            }

            override fun onPartialGranted() {
            }

            override fun onAllRejected() {
                AndroidUtil.openAppNotifySettings()
            }
        })
    }


    private fun handleDailyVideoButClicked(itemIndex: Int) {
        val subTaskList = TaskManager.instance().dailyWatchVideoStatus().getStatusBean().getSubTaskRewardState()
        if (itemIndex >= 0 && itemIndex < subTaskList.size) {
            val subTaskState = subTaskList[itemIndex]
            when (subTaskState.state) {
                STATE_ONGOING -> {
                    val activity = requireActivity()
                    if (activity is MainActivity) {
                        activity.switchTab(0)
                    }
                }
                STATE_FINISH -> {
                    if (TaskManager.instance().dailyWatchVideoStatus().claimSubTaskReward(itemIndex, false)) {
                        DailySignSuccessDialog(requireActivity()).initData(subTaskState.mRewardNum, false).show()
                    }
                }
            }
        }
    }

    private fun handleDailyAdButClicked(itemIndex: Int) {
        val subTaskList = TaskManager.instance().dailyWatchAdStatus().getStatusBean().getSubTaskRewardState()
        if (itemIndex >= 0 && itemIndex < subTaskList.size) {
            val subTaskState = subTaskList[itemIndex]
            when (subTaskState.state) {
                STATE_ONGOING -> {
                    WatchAdDialog(requireActivity(), VidiConst.WATCH_AD_FOR_DAILY_WATCH_AD, WatchAdDialog.FROM_DIALY_TASKS, null).show()
                }
                STATE_FINISH -> {
                    if (TaskManager.instance().dailyWatchAdStatus().claimSubTaskReward(itemIndex, true)) {
                        DailySignSuccessDialog(requireActivity()).initData(subTaskState.mRewardNum, false).show()
                    }
                }
            }
        }
    }


    private fun showGuide1() {
        HighlightPro.with(this@TasksFragment)
            .setHighlightParameter {
                HighlightParameter.Builder()
                    .setHighlightView(binding!!.goldContainer, {
                        delayConvertGold2Cash()
                    })
                    .setTipsViewId(R.layout.guide_step_gold)
                    .setHighlightShape(RectShape(10.dp, 10.dp, 10.dp))
                    .setHighlightHorizontalPadding(0.dp)
                    .setConstraints(Constraints.TopToBottomOfHighlight + Constraints.StartToStartOfHighlight)
                    .setMarginOffset(MarginOffset(top = -20.dp.toInt()))
                    .build()
            }
            .setHighlightParameter {
                HighlightParameter.Builder()
                    .setHighlightView(binding!!.cashContainer, {
                        val temp = 111
                    })
                    .setTipsViewId(R.layout.guide_step_cash)
                    .setHighlightShape(RectShape(10.dp, 10.dp, 10.dp))
                    .setHighlightHorizontalPadding(0.dp)
                    .setConstraints(Constraints.TopToBottomOfHighlight + Constraints.EndToEndOfHighlight)
                    .setMarginOffset(MarginOffset(top = -20.dp.toInt()))
                    .build()
            }
            .setBackgroundColor("#cc000000".toColorInt())
            .setOnShowCallback { index ->

            }
            .setOnDismissCallback {
                binding?.ivAdIndi?.isVisible = true
                GuideManager.instance().setGuideIndex(VidiConst.GUIDE_INDEX_CASH_GOLD)
                gotoWithDraw()
            }
            .interceptBackPressed(true)
            .show()

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

    private fun delayConvertGold2Cash() {
        binding?.tvCashTotal?.postDelayed({
            AccountManager.convertGold2Cash()
        }, 200)
    }

    private fun showGuide2() {
        HighlightPro.with(this@TasksFragment)
            .setHighlightParameter {
                HighlightParameter.Builder()
                    .setHighlightView(binding!!.flZeroBug, {
                        val temp = 111
                    })
                    .setTipsViewId(R.layout.guide_step_zerobuy)
                    .setHighlightShape(OvalShape())
                    .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 {
                GuideManager.instance().setGuideIndex(VidiConst.GUIDE_INDEX_ZERO)
                gotoZeroBuy()
            }
            .interceptBackPressed(true)
            .show()

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

}