package com.swiftcleaner.chovey.view.activity

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.business.admob.AdmobManager.isShowAdBackInter
import com.swiftcleaner.chovey.business.admob.AdmobManager.isShowAdInter
import com.swiftcleaner.chovey.business.admob.AdmobManager.showInterstitialAd
import com.swiftcleaner.chovey.business.admob.AdmobManager.showNativeAd
import com.swiftcleaner.chovey.databinding.ActivityMalwareCleanBinding
import com.swiftcleaner.chovey.databinding.DialogErrBinding
import com.swiftcleaner.chovey.databinding.ItemMalwareCleanBinding
import com.swiftcleaner.chovey.model.bean.AppInfoBean
import com.swiftcleaner.chovey.model.tool.FileHelps
import com.swiftcleaner.chovey.model.util.FinishMain.finishToMain
import com.swiftcleaner.chovey.util.ActivityLauncher
import com.swiftcleaner.chovey.util.CloudScan
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog
import com.trustlook.sdk.cloudscan.CloudScanListener
import com.trustlook.sdk.data.AppInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

class MalwareCleanActivity : AppCompatActivity() {

    private val binding by lazy(LazyThreadSafetyMode.NONE) {
        ActivityMalwareCleanBinding.inflate(layoutInflater)
    }

    private var appList = mutableListOf<AppInfoBean>()
    private val adapter by lazy(LazyThreadSafetyMode.NONE) {
        class ViewHolder(val binding: ItemMalwareCleanBinding) :
            RecyclerView.ViewHolder(binding.root)

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val binding = ItemMalwareCleanBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                return ViewHolder(binding)
            }

            override fun getItemCount(): Int = appList.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = appList[position]
                holder.binding.ivIcon.setImageDrawable(item.appIcon)
                holder.binding.tvName.text = item.appName
                holder.binding.tvLevel.text = getLevel(item.score ?: 0)
                holder.binding.viewLine.visibility =
                    if (position == itemCount - 1) View.GONE else View.VISIBLE
                holder.itemView.setOnClickListener {
                    item.isSelected = !item.isSelected

                    if (isShowAdInter()) {
                        showInterstitialAd(this@MalwareCleanActivity, dismissed = {
                            uninstall(0, listOf(item))
                        }, failed = {
                            uninstall(0, listOf(item))
                        }, isRetry = false)
                    }
                }
            }
        }

    }

    private fun getLevel(score: Int): String {
        return if (score <= 5) {
            "safe"
        } else if (score in 6..7) {
            "Risk"
        } else {
            "malware"
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initBar()
        setContentView(binding.root)
        initView()
        onBackPressedDispatcher.addCallback {
            initCustomDialog()
        }
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initView() {
        binding.clRadarview.isVisible = true
        binding.radarview.setSearching(true)
        showNativeAd(this, { nativeAd: NativeAd? ->
            nativeAd?.let {
                binding.flAdDonghua.removeAllViews()
                binding.flAdDonghua.setNativeAd(nativeAd, R.layout.layout_ad_native)
            }
        }, null, null)
        if (isShowAdInter()) {
            showInterstitialAd(this@MalwareCleanActivity, dismissed = {
                initData(false)
            }, failed = {
                initData(false)
            }, isRetry = false)
        }
        binding.rvMalware.adapter = adapter
        binding.rvMalware.layoutManager = LinearLayoutManager(this)

        binding.flBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.tvDelete.setOnClickListener {

            val list = appList.filter { it.isSelected }
            if (list.isNotEmpty()) {
                binding.tvDelete.isEnabled = false
                malwareClean(list)
            }
        }
    }

    private var isScanning = true

    private fun scanFinish() {
        isScanning = false
        binding.clRadarview.isVisible = false
        binding.radarview.setSearching(false)
    }

    private fun initData(isScan: Boolean = isScanning) {
        if (isScan) return
        isScanning = true
        CloudScan.scanClient.startQuickScan(object : CloudScanListener() {
            override fun onScanStarted() {
                // Log.e("CloudScan","onScanStarted")
            }

            override fun onScanCanceled() {
                scanFinish()
                // Log.e("CloudScan","onScanCanceled")
            }

            override fun onScanProgress(current: Int, total: Int, p2: AppInfo?) {
            }

            override fun onScanFinished(dataList: MutableList<AppInfo>?) {

                //Log.e("CloudScan", "onScanFinished")
                lifecycleScope.launch(Dispatchers.Default) {
                    val realList = mutableListOf<AppInfoBean>()
                    dataList?.forEach {
                        if (!it.isSystemApp
                            && it.score > 5
                        ) {
                            var isInstall: Boolean
                            // Log.e("CloudScan", "${it.source}  ${it.apkPath}  ${it.toJSON(this@MalwareCleanActivity)}")
                            val icon = try {
                                val res = packageManager.getApplicationIcon(it.packageName)
                                isInstall = true
                                res
                            } catch (e: PackageManager.NameNotFoundException) {
                                isInstall = false
                                val info = packageManager.getPackageArchiveInfo(
                                    it.apkPath,
                                    PackageManager.GET_ACTIVITIES
                                )
                                if (info != null) {
                                    packageManager.getApplicationIcon(info.applicationInfo)
                                } else {
                                    AppCompatResources.getDrawable(
                                        this@MalwareCleanActivity,
                                        R.mipmap.l_apk
                                    )
                                }
                            }
                            realList.add(
                                AppInfoBean(
                                    it.appName,
                                    icon!!,
                                    it.packageName,
                                    false,
                                    isInstall,
                                    it.score,
                                    it.apkPath
                                )
                            )
//                            withContext(Dispatchers.Main) {
//                                adapter.notifyItemInserted(appList.size)
//                            }
                        }
                    }
                    withContext(Dispatchers.Main) {
                        val durationTime = Random.nextLong(3000, 3500)
                        delay(durationTime)
                        appList.clear()
                        appList.addAll(realList)
                        scanFinish()
                        adapter.notifyDataSetChanged()
                        updateView()

                    }
                }
            }

            override fun onScanError(p0: Int, p1: String?) {
                isScanning = false
                showErrDialog(this@MalwareCleanActivity) {
                    finishToMain(this@MalwareCleanActivity)
                }
            }

            override fun onScanInterrupt() {
                isScanning = false
                showErrDialog(this@MalwareCleanActivity) {
                    finishToMain(this@MalwareCleanActivity)
                }
            }
        })
    }

    fun showErrDialog(
        context: Activity,
        confirm: () -> Unit
    ) {
        val binding = DialogErrBinding.inflate(LayoutInflater.from(context))
        val dialog = Dialog(context, R.style.TransparentDialogTheme).apply {
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            setContentView(binding.root)
            show()
        }
        binding.tvSure.setOnClickListener {
            it.isEnabled = false
            dialog.dismiss()
            confirm.invoke()
        }
        showNativeAd(
            context,
            completed = {
                binding.adNative.setExitNativeAd(it)
            }
        )
    }

    private fun updateView() {
        binding.ivLogo.visibility = if (appList.isEmpty()) View.GONE else View.VISIBLE
        binding.tvCount.visibility = if (appList.isEmpty()) View.GONE else {
            binding.tvCount.text = "${appList.size} issue"
            View.VISIBLE
        }
        binding.tvUnit.visibility = if (appList.isEmpty()) View.GONE else View.VISIBLE
        binding.rvMalware.visibility = if (appList.isEmpty()) View.GONE else View.VISIBLE
        binding.ivEmpty.visibility = if (appList.isEmpty()) View.VISIBLE else View.GONE
        if (appList.isEmpty()) {
            // actionCleanResult(0, getString(R.string.malware_scan))
        } else {
            showNativeAd(this, { nativeAd: NativeAd? ->
                nativeAd?.let {
                    binding.adNative.removeAllViews()
                    binding.adNative.setNativeAd(nativeAd, R.layout.layout_ad_native)
                }
            }, null, null)
        }
    }


    private fun malwareClean(list: List<AppInfoBean>) {
        lifecycleScope.launch(Dispatchers.Default) {
            val installApps = mutableListOf<AppInfoBean>()
            list.forEach {
                if (it.isInstall == true) installApps.add(it)
                else {
                    it.apkPath?.also {
                        launch(Dispatchers.IO) {
                            FileHelps.deleteFile(it)
                        }
                    }
                    appList.remove(it)
                }
            }

            if (installApps.isNotEmpty()) {
                uninstall(0, installApps)
            } else {
                withContext(Dispatchers.Main) {
                    adapter.notifyDataSetChanged()
                    updateUninstall()
                }
            }
        }
    }

    private fun uninstall(position: Int, list: List<AppInfoBean>) {
        val packageName = list[position].packageName
        val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:$packageName"))
        ActivityLauncher(this).launch(intent) {
            if (isUninstall(packageName)) {
                appList.removeIf { it.packageName == packageName }
                runOnUiThread {
                    adapter.notifyDataSetChanged()
                    updateUninstall()
                }
            }
            if (position < list.size - 1) uninstall(position + 1, list)
            else runOnUiThread { binding.tvDelete.isEnabled = true }
        }
    }

    private fun isUninstall(packageName: String): Boolean {
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        return intent == null
    }

    private fun updateUninstall() {
        val list = appList.filter { it.isSelected }
        val size = if (list.isEmpty()) "" else " ${list.size} Apps"
        binding.tvDelete.text = "${getString(R.string.uninstall)}${size}"
        // ResourceUtils.setTextBackground(binding.tvDelete, list.isNotEmpty())
    }

    private fun initCustomDialog() {
        val activity: Activity = this
        val customScoreDialog = CustomScoreDialog(this)
        customScoreDialog.setOnDialogClickListener(object :
            CustomScoreDialog.OnDialogClickListener {
            override fun onCancel() {
                customScoreDialog.dismiss()
            }

            override fun onSubmit() {
                if (isShowAdBackInter()) {
                    showInterstitialAd(
                        this@MalwareCleanActivity, {
                            finishToMain(activity)
                            null
                        },
                        { null },
                        {
                            finishToMain(activity)
                            null
                        }, false
                    )
                } else {
                    finishToMain(activity)
                }
            }
        })
        customScoreDialog.show()
    }

    private fun initBar() {
        ImmersionBar.with(this)
            .transparentStatusBar() // 透明状态栏
            .statusBarDarkFont(false) // 状态栏字体颜色为深色
            .navigationBarDarkIcon(true) // 导航栏图标颜色为浅色
            .init()
        binding.clTop.updatePadding(top = ImmersionBar.getStatusBarHeight(this))
    }
}