package com.base.scanqrclear.luma

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.airbnb.lottie.LottieAnimationView
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.bean.FileBean
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.helper.EventUtils
import com.base.scanqrclear.luma.AdmobHelps.KEY_CLEANUP_SIZE
import com.base.scanqrclear.luma.DialogHelps.showExitDialog
import com.base.scanqrclear.ui.main.MainActivity
import com.base.scanqrclear.utils.ActivityLauncher
import com.base.scanqrclear.utils.ExitType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

open class BaseActivity2 : AppCompatActivity() {

    protected lateinit var launcher: ActivityLauncher

    protected var loadingDialog: Dialog? = null

    protected var isDisableBack = false
    private var isShowAdInterstitial = false

    private var isPause = false
    private var lottieType: LottieType? = null
    private var complete: (() -> Unit?)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launcher = ActivityLauncher(this)
        immersive()
        ActivityManagerHelps.add(this)
        EventUtils.event("${javaClass.simpleName}_show")
    }

    override fun onResume() {
        super.onResume()
        isPause = false
//        if (isShowAdInterstitial) {
//            lifecycleScope.launch {
//                delay(1000)
//                startAdInterstitial()
//            }
//        }
    }

    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityManagerHelps.remove(this)
        lottieType = null
        complete = null
    }

    protected open fun immersive() {
        StatusBarHelps.immersive(this, getColor(R.color.color_8eb0ff))
    }

    protected fun showAnimationAd(
        lottieType: LottieType = LottieType.CLEAN,
        isShowAnimation: Boolean = true,
        complete: (() -> Unit?)? = null
    ) {
        this.lottieType = lottieType
        this.complete = complete
        showAdInterstitial(AdmobHelps.isShowAdInter()) {
            val animationView = findViewById<ConstraintLayout>(R.id.animation)
            animationView.setOnClickListener { }
            if (isShowAnimation) {
                StatusBarHelps.immersive(this, getColor(R.color.color_8eb0ff))
                showAnimation(animationView, lottieType, complete)
            } else {
                complete?.invoke()
            }
        }
    }


    protected fun showAdInterstitial(isShow: Boolean, complete: (() -> Unit?)? = null) {
        if (this.isFinishing || this.isDestroyed || isShowAdInterstitial) return
        isShowAdInterstitial = true
        if (isShow) {
            AdmobHelps.showInterstitialAd(
                this,
                dismissed = {
                    clearLoading()
                    immersive()
                    complete?.invoke()
                },
                completed = {
                    StatusBarHelps.immersive(this, getColor(R.color.black))
                    loadingDialog?.dismiss()
                },
                failed = {
                    clearLoading()
                    immersive()
                    complete?.invoke()
                }
            )
        } else {
            isShowAdInterstitial = false
            complete?.invoke()
        }
    }

    protected fun showAnimation(
        view: View,
        lottieType: LottieType,
        complete: (() -> Unit?)? = null
    ) {
        isDisableBack = true
        view.visibility = View.VISIBLE
        val progress = view.findViewById<androidx.appcompat.widget.AppCompatTextView>(R.id.tv_progress)
        progress.text = "0%"
        val lottie = view.findViewById<LottieAnimationView>(R.id.lottie_animation)
        lottie.setAnimation(lottieType.data)
        lottie.loop(isLoop(lottieType))
        lottie.playAnimation()
        if (!lottieType.images.isNullOrEmpty())
            lottie.imageAssetsFolder = lottieType.images

        if (!isLoop(lottieType)) {
            lottie.addAnimatorUpdateListener { animation ->
                val value = animation.animatedValue as Float * 100
                progress.text = "${value.toInt()}%"
                if (value.toInt() == 100) {
                    view.visibility = View.GONE
                    complete?.invoke()
                    isDisableBack = false
                }
            }
            return
        }

        lifecycleScope.launch(Dispatchers.Main) {
            val durationTime = Random.Default.nextLong(3000, 3500)
            ValueAnimator.ofInt(0, 100).apply {
                duration = durationTime
                interpolator = LinearInterpolator()
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Int
                    progress.text = "${value}%"
                }
                addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        view.visibility = View.GONE
                        complete?.invoke()
                        isDisableBack = false
                        lottie.cancelAnimation()
                    }
                })
            }.start()
        }
    }

    private fun isLoop(lottieType: LottieType): Boolean {
        return lottieType != LottieType.CLEAN
    }

    private fun clearLoading() {
        loadingDialog?.dismiss()
        loadingDialog = null
        isShowAdInterstitial = false
    }

    protected fun cleanFiles(list: List<FileBean>) {
        lifecycleScope.launch(Dispatchers.IO) {
            val paths = list.filter { it.isSelected }.map { it.path }.toTypedArray()
            paths.forEach { FileHelps.deleteFile(it) }
            withContext(Dispatchers.Main) {
                MediaHelps.updateMedia(applicationContext, paths)
            }
        }
    }

    protected fun toCleanResult(size: Long, titleName: String) {
        val cleanupSize = SpUtils.getInstance().getLong(KEY_CLEANUP_SIZE)
        SpUtils.getInstance().putLong(KEY_CLEANUP_SIZE, cleanupSize + size)
        CleanResultActivity.start(this, size, titleName)
        ActivityManagerHelps.finishAll(MainActivity::class.java)
    }

    protected fun backPressed() {
        onBackPressedDispatcher.onBackPressed()
    }

    fun handleBackPressed(activity: Activity) {
        when (activity) {
            is MainActivity -> logout()
            is CleanJunkActivity -> exit(ExitType.CLEAN)
            is SimilarPhotosActivity -> exit(ExitType.SIMILAR_PHOTOS)

            is ScreenshotCleanActivity -> exit(ExitType.SCREENSHOT)

            is WhatsappCleanActivity -> exit(ExitType.WHATSAPP)
            is WhatsappCleanDetailActivity -> exit(ExitType.WHATSAPP)

            is AppProcessActivity -> exit(ExitType.APP_PROCESS)
            else -> finishToMainTop()
        }
    }

    private fun logout() {
        DialogHelps.showLogoutDialog(this, {
            ActivityManagerHelps.finishAll()
//            exitProcess(0)
        }, {
            ActivityJumpHelps.start(this, launcher, R.string.junk_scan)
        })
    }


    private fun exit(exit: ExitType) {
        showExitDialog(this, getString(exit.title), getString(exit.content)) {
            backAdJump()
        }
    }

    fun backAdJump() {
        if (AdConfigBean.adsConfigBean.functionBackShowAd) {
            AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    finishToMainTop()
                }

                override fun failed(where: Int) {
                    finishToMainTop()
                }

                override fun googleFailed(where: Int) {
                    finishToMainTop()
                }
            })
        } else {
            finishToMainTop()
        }
    }

    fun finishToMainTop() {
        val intent = Intent(this, MainActivity::class.java)
        intent.putExtra("where", "finishToMainTop")
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
        finish()
    }
}