package com.gamedog.vididin.features.benefit

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.activity.viewModels
import com.ama.core.architecture.appBase.AppViewsActivity
import com.ama.core.architecture.util.ResUtil
import com.gamedog.vididin.R
import com.gamedog.vididin.VididinEvents
import com.gamedog.vididin.features.benefit.widget.BenefitTaskItemView
import com.gamedog.vididin.main.interfaces.OnTabStyleListener
import com.gamedog.vididin.manager.TaskManager
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_AD
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_VIDEO
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_SIGN
import com.gamedog.vididin.manager.TaskManager.Companion.BOX_SUB_TASK_TYPE_ZERO_BUY
import dagger.hilt.android.AndroidEntryPoint
import kotlin.getValue
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_FINISH
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_CLAIMED
import com.gamedog.vididin.manager.taskbeans.BaseTaskState.Companion.STATE_EXPIRED
import com.gamedog.vididin.router.Router
import com.gamedog.vididin.databinding.ActivityBenefitBinding as ViewBinding
import com.gamedog.vididin.main.MainUiState as UiState
import com.gamedog.vididin.main.MainViewModel as ViewModel


@AndroidEntryPoint
class BenefitActivity : AppViewsActivity<ViewBinding, UiState, ViewModel>(), OnTabStyleListener {

    private val mSubTaskViewList = mutableListOf<BenefitTaskItemView>()


    override val mViewModel: ViewModel by viewModels()
    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)

    override fun ViewBinding.initWindowInsets() {
        setImmerseRootView(contentRoot)
    }


    override fun ViewBinding.initViews() {
        titlebar.setTitleText(R.string.benefit)
        initViewsByTaskState()
    }

    override fun ViewBinding.initListeners() {

    }

    override fun ViewBinding.initObservers() {

    }

    override fun ViewBinding.onUiStateCollect(uiState: UiState) {

    }

    override fun onTabIsDarkFont(isDarkFont: Boolean) {

    }


    private fun initViewsByTaskState() {
        initAddSubTaskViews()
        updateSubTasksUI()
        updateTopBoxesUI()
    }

    private fun initAddSubTaskViews() {
        val taskStateHelper = TaskManager.instance().boxTaskStatus()
        val currentBoxState = taskStateHelper.getStatusBean().tasks[taskStateHelper.getCurrentBoxIndex()]

        currentBoxState.tasks.forEachIndexed { index, subTask ->
            val separateLine = View(this@BenefitActivity)
            separateLine.setBackgroundResource(R.color.gray_f2)
            binding.llSubTaskContainer.addView(separateLine, ViewGroup.LayoutParams.MATCH_PARENT, ResUtil.getPixelSize(R.dimen.dp1))

            val subTaskView = BenefitTaskItemView(this@BenefitActivity)
            subTaskView.setActionFun { handleActionButClicked(subTask.task_type) }
            val subViewParam = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            subViewParam.topMargin = ResUtil.getPixelSize(R.dimen.dp10)
            subViewParam.bottomMargin = ResUtil.getPixelSize(R.dimen.dp10)
            binding.llSubTaskContainer.addView(subTaskView, subViewParam)

            mSubTaskViewList.add(subTaskView)
        }
    }

    private fun handleActionButClicked(taskType: Int) {
        when (taskType) {
            BOX_SUB_TASK_TYPE_AD -> {
                Router.WatchAd.startActivity(this@BenefitActivity, VididinEvents.Event_AD_TASK_TYPE_BOX_TASK, null)
            }

            BOX_SUB_TASK_TYPE_SIGN -> {
                // TODO -
            }

            BOX_SUB_TASK_TYPE_VIDEO -> {

            }

            BOX_SUB_TASK_TYPE_ZERO_BUY -> {
                Router.ZeroBuy.startActivity(this@BenefitActivity)
            }
        }

        finish()
    }

    private fun updateSubTasksUI() {
        val taskStateHelper = TaskManager.instance().boxTaskStatus()
        val currentBoxIndex = taskStateHelper.getCurrentBoxIndex()
        val subTaskStateList = taskStateHelper.getStatusBean().tasks[currentBoxIndex].tasks

        if (subTaskStateList.size == mSubTaskViewList.size) {
            mSubTaskViewList.forEachIndexed { index, view ->
                view.updateUIByState(subTaskStateList[index], currentBoxIndex,index)
            }
        }
    }

    private fun updateTopBoxesUI() {
        val taskStateHelper = TaskManager.instance().boxTaskStatus()
        val boxStateList = taskStateHelper.getStatusBean().tasks

        with (binding) {
            boxStateList.forEachIndexed { index, curBoxState ->
                val stateEnum = taskStateHelper.getBoxStateEnum(index)
                if (index == 0) {
                    ivSubtask1.setImageResource(getIconResByState(stateEnum))
                    tvSubtask1State.setText(getStrResByState(stateEnum))
                    tvSubtask1State.setTextColor(getStrColorByState(stateEnum))

                    with (tvSubtask1Reward) {
                        compoundDrawablePadding = if (stateEnum == STATE_FINISH || stateEnum == STATE_CLAIMED) 0 else ResUtil.getPixelSize(R.dimen.dp3)
                        val tvRewardIcon = getRewardTvDrawableRes(stateEnum)
                        setCompoundDrawables(ResUtil.getDrawable(tvRewardIcon), null, null, null)
                        val needShowNum = R.mipmap.icon_check_mark != tvRewardIcon
                        setText(if (needShowNum) { ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value}  else "")
                    }
                }

                if (index == 1) {
                    ivSubtask2.setImageResource(getIconResByState(stateEnum))
                    tvSubtask2State.setText(getStrResByState(stateEnum))
                    tvSubtask2State.setTextColor(getStrColorByState(stateEnum))

                    with (tvSubtask2Reward) {
                        compoundDrawablePadding = if (stateEnum == STATE_FINISH || stateEnum == STATE_CLAIMED) 0 else ResUtil.getPixelSize(R.dimen.dp3)
                        val tvRewardIcon = getRewardTvDrawableRes(stateEnum)
                        setCompoundDrawables(ResUtil.getDrawable(tvRewardIcon), null, null, null)
                        val needShowNum = R.mipmap.icon_check_mark != tvRewardIcon
                        setText(if (needShowNum) { ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value}  else "")
                    }
                }

                if (index == 2) {
                    ivSubtask3.setImageResource(getIconResByState(stateEnum))
                    tvSubtask3State.setText(getStrResByState(stateEnum))
                    tvSubtask3State.setTextColor(getStrColorByState(stateEnum))

                    with (tvSubtask3Reward) {
                        compoundDrawablePadding = if (stateEnum == STATE_FINISH || stateEnum == STATE_CLAIMED) 0 else ResUtil.getPixelSize(R.dimen.dp3)
                        val tvRewardIcon = getRewardTvDrawableRes(stateEnum)
                        setCompoundDrawables(ResUtil.getDrawable(tvRewardIcon), null, null, null)
                        val needShowNum = R.mipmap.icon_check_mark != tvRewardIcon
                        setText(if (needShowNum) { ResUtil.getString(R.string.cash)  + " " + curBoxState.reward_value}  else "")
                    }
                }
            }

            val couldClaimCashNum = taskStateHelper.getCouldClaimCashNum()
            with (tvResgatar) {
                if (couldClaimCashNum > 0) {
                    (R.mipmap.icon_but_bg_green)
                    isClickable = true
                } else {
                    setBackgroundResource(R.mipmap.but_bg_grady)
                    isClickable = false
                }
            }


            // 总进度条, 奖励金额
            val totalProgress = taskStateHelper.getCurrentBoxTotalProgress()
            progressTasks.setProgress(totalProgress)
            tvProgressNum.text = "($totalProgress%)"
            tvHintRewardNum.text = buildString {
                append(ResUtil.getString(R.string.cash))
                append(" ")
                append(taskStateHelper.getStatusBean().tasks[taskStateHelper.getCurrentBoxIndex()].reward_value)
            }
        }
    }

    private fun getIconResByState(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.mipmap.benefit_item_expired
            STATE_FINISH, STATE_CLAIMED -> return R.mipmap.benefit_item_finished
            else -> return R.mipmap.benefit_item_ongoing
        }
    }

    private fun getStrResByState(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.string.expired
            STATE_FINISH, STATE_CLAIMED -> return R.string.finished
            else -> return R.string.ongoing
        }
    }

    private fun getStrColorByState(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.color.gray_60
            STATE_FINISH, STATE_CLAIMED -> return R.color.green_39
            else -> return R.color.red_5c
        }
    }

    private fun getRewardTvDrawableRes(state: Int): Int {
        when (state) {
            STATE_EXPIRED -> return R.mipmap.icon_cash_s_disable
            STATE_FINISH, STATE_CLAIMED -> return R.mipmap.icon_check_mark
            else -> return R.mipmap.icon_cash_s
        }
    }


    companion object {
        internal fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity.applicationContext, BenefitActivity::class.java))
        }
    }

}