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 android.widget.Toast
import androidx.activity.addCallback
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.helper.EventUtils
import com.base.scanqrclear.luma.AdmobHelps.KEY_CLEANUP_SIZE
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
    protected var isExit = 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()
        //todo 返回
//        addBackPressedCallback()
        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)
        isExit = false
        lottieType = null
        complete = null
    }

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

    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_ffb764))
                showAnimation(animationView, lottieType, complete)
            } else {
                complete?.invoke()
            }
        }
//        if (isShowAnimation) {
//            StatusBarHelps.immersive(this, getColor(R.color.color_ffb764))
//            val animationView = findViewById<ConstraintLayout>(R.id.animation)
//            showAnimation(animationView, lottieType) { startAdInterstitial() }
//        } else {
//            startAdInterstitial()
//        }
    }

//    protected fun startAdInterstitial() {
//        if (this is SplashActivity || this is MainActivity) return
//        isShowAdInterstitial = true
//        if (!isPause) {
//            val animationView = findViewById<ConstraintLayout>(R.id.animation)
//            showAdInterstitial(animationView, complete)
//        }
//    }

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

    protected open fun handleBackPressed(activity: Activity) {
        when (activity) {
            is MainActivity -> logout()
//            is AppManagerActivity -> exit(ExitType.APP_MANAGER)
//            is BatteryInfoActivity -> exit(ExitType.BATTERY_INFO)
//            is CleanJunkActivity -> exit(ExitType.CLEAN)
//            is LargeFileCleanActivity -> exit(ExitType.LARGE_FILE)
//            is com.base.scanqrclear.luma.ScreenshotCleanActivity -> exit(ExitType.SCREENSHOT)
//            is com.base.scanqrclear.luma.SimilarPhotosActivity -> exit(ExitType.SIMILAR_PHOTOS)
//            is com.base.scanqrclear.luma.WhatsappCleanActivity -> exit(ExitType.WHATSAPP)
//            is PhotoCompressionActivity -> exit(ExitType.PHOTO_COMPRESSION)
//            else -> finishOrToMain()
        }
    }

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

    protected fun showExitDialog(title: String, content: CharSequence) {
        if (isExit) return
        isExit = true
        DialogHelps.showExitDialog(
            this,
            title,
            content,
            { showAdInterstitial(AdmobHelps.isShowAdBackInter()) { finishOrToMain() } },
            { isExit = false }
        )
    }

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

    private fun addBackPressedCallback(activity: Activity) {
        onBackPressedDispatcher.addCallback {
            if (isDisableBack) {
                Toast.makeText(applicationContext, getString(R.string.wait_a_moment), Toast.LENGTH_SHORT).show()
            } else {
                if (isShowAdInterstitial) return@addCallback
                handleBackPressed(activity)
            }
        }
    }

    protected fun finishOrToMain() {
//        if (this !is MainActivity
//            && !ActivityManagerHelps.isActivityInStack(MainActivity::class.java)
//        ) {
//            MainActivity.start(this)
//        }
//        finish()
    }

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