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.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
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.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.gamedog.vididin.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 dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.getValue
import com.gamedog.vididin.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 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(root) { v, insets ->
            val systemBars =
                insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())
            v.updatePadding(top = systemBars.top)
            insets
        }
    }


    override fun ViewBinding.initViews() {
        with(binding) {
            setOnClickBatch(ivGotoDailySign, llTaskBenefit, llTaskWatchVideo, llTaskGame,
                llTaskZerobuy, tvWatchVideoForConvertGoldToCash, tvWithdraw) {
                when(this) {
                    ivGotoDailySign->{
                        DailySignDialog(requireActivity()).show()
                    }

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

                    llTaskWatchVideo->{
                        WatchAdDialog(requireActivity(), VididinEvents.Event_AD_TASK_TYPE_Watch_Ad_Earn_Gold, null).show()
                    }

                    llTaskGame->{

                    }

                    llTaskZerobuy->{
                        Router.ZeroBuy.startActivity(requireActivity())
                    }

                    tvWatchVideoForConvertGoldToCash->{
                        WatchAdDialog(requireActivity(), VididinEvents.Event_AD_TASK_TYPE_Convert_Gold_2_Cash, null).show()
                    }

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



            with(beginnerTaskWithdraw) {
                initUI(R.mipmap.icon_cash_s, R.string.beginner_withdraw_title, R.string.beginner_withdraw_desc,R.string.resgatar)
                //setRewardTextStyle(21, R.color.green_39)
                setActionFun {
                    gotoWithDraw()
                }
                setRewardInfo(TaskManager.instance().getNewbieFirstWithdrawTask()!!)
            }


            with(beginnerTaskDiscord) {
                initUI(R.mipmap.icon_dicord, R.string.beginner_discord_title, R.string.beginner_discord_desc,R.string.resgatar)
                setActionFun {
                    gotoDiscord()
                }
                setRewardInfo(TaskManager.instance().getNewbieJoinDiscordTask()!!)
            }

            with(beginnerTaskEnableNotify) {
                initUI(R.mipmap.icon_notify, R.string.beginner_notify_title, R.string.beginner_notify_desc,R.string.Resgatado)
                beginnerTaskEnableNotify.setActionFun {
                    gotoNotification()
                }
                setRewardInfo(TaskManager.instance().getNewbieEnableNotifyTask()!!)
            }


            addDailySubTasks()

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

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

    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(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 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 -> {
                    scroll2FirstWithdraw()
                }
            }
        }, 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)
    }

    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))
            }
        }
    }

    override fun ViewBinding.initObservers() {
    }

    override fun ViewBinding.onUiStateCollect(uiState: UiState) {

    }

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

    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() {
                AndroidUtil.openAppNotifySettings()
            }

            override fun onPartialGranted() {
            }

            override fun onAllRejected() {
            }
        })
    }

    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)) {
                        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(), VididinEvents.Event_AD_TASK_TYPE_Watch_Ad_Daily, null).show()
                }
                STATE_FINISH -> {
                    if (TaskManager.instance().dailyWatchAdStatus().claimSubTaskReward(itemIndex)) {
                        DailySignSuccessDialog(requireActivity()).initData(subTaskState.mRewardNum, false).show()
                    }
                }
            }
        }
    }


}