package com.easy.clean.ui.videoclean

import android.annotation.SuppressLint
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.easy.clean.R
import com.easy.clean.base.BaseActivity
import com.easy.clean.base.LottieEnum
import com.easy.clean.base.cleanFileBeans
import com.easy.clean.bean.FeatureBean.Companion.SCREENSHOT_CLEAN
import com.easy.clean.bean.FileBean
import com.easy.clean.business.ads.AdsMgr
import com.easy.clean.business.ads.AdsShowCallBack
import com.easy.clean.databinding.ActivityVideoCleanBinding
import com.easy.clean.databinding.ItemVideoBinding
import com.easy.clean.ui.cleanresult.CleanResultActivity
import com.easy.clean.ui.dialog.ConfirmDialog
import com.easy.clean.utils.MediaUtils
import com.easy.clean.utils.Utils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class VideoCleanActivity :
    BaseActivity<ActivityVideoCleanBinding>(ActivityVideoCleanBinding::inflate) {


    private var list = mutableListOf<FileBean>()
    private var isSelectAll = false
    private var total: Long = 0
    private var selectedFiles = listOf<FileBean>()

    private val adapter by lazy {
        class VideoHolder(val item: ItemVideoBinding) : RecyclerView.ViewHolder(item.root)
        object : RecyclerView.Adapter<VideoHolder>() {
            override fun onCreateViewHolder(
                parent: ViewGroup,
                viewType: Int,
            ): VideoHolder {
                val binding = ItemVideoBinding.inflate(layoutInflater, parent, false)
                return VideoHolder(binding)
            }

            override fun onBindViewHolder(holder: VideoHolder, position: Int) {
                val bean = list[position]
                val round = resources.getDimensionPixelSize(R.dimen.dp_8)
                val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
                Glide.with(holder.itemView.context)
                    .asBitmap()
                    .load(File(bean.path))
                    .apply(options)
                    .into(holder.item.ivPreview)
                holder.item.tvSize.text = Utils.getSizeFormat(bean.length)
                holder.item.ivSelect.isSelected = bean.isSelected
                holder.item.root.setOnClickListener {
                    val f = !bean.isSelected
                    holder.item.ivSelect.isSelected = f
                    bean.isSelected = f
                    updateSelection()
                }
            }

            override fun getItemCount() = list.size
        }
    }

    private fun updateSelection() {
        selectedFiles = list.filter {
            it.isSelected
        }
        isSelectAll = selectedFiles.size == list.size
        total = selectedFiles.sumOf { it.length }
        updateView(selectedFiles.isNotEmpty())
    }


    private fun updateView(isSelection: Boolean) {

        binding.ivSelectAll.isSelected = isSelectAll
        binding.tvDelete.isEnabled = isSelection
        if (total > 0) {
            binding.tvDelete.setTextColor(getColor(R.color.white))
            binding.tvDelete.text =
                "${getString(R.string.delete)} (${Utils.getSizeFormat(total)})"
            binding.tvDelete.background = getDrawable(R.drawable.bg_primary_r4)
        } else {
            binding.tvDelete.setTextColor(getColor(R.color.fontsBlack))
            binding.tvDelete.text = getString(R.string.delete)
            binding.tvDelete.background = getDrawable(R.drawable.bg_f2f5f6_r4)
        }
    }

    override fun useDefaultImmersive() {
        setStatusBarColor()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            binding.clTop.setPadding(0, systemBars.top, 0, 0)
            insets
        }
    }

    override fun initView() {
        super.initView()
        binding.expandableFiles.adapter = adapter
        val gridLayoutManager = GridLayoutManager(this, 3)
        binding.expandableFiles.layoutManager = gridLayoutManager
        initData()

        showAdAnimation(LottieEnum.VIDEO_CLEAN_LOTTIE) {
            AdsMgr.showNative(binding.flAd, R.layout.layout_admob_native_custom)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            list = MediaUtils.findVideoFiles(this@VideoCleanActivity)
            updateSelection()
            adapter.notifyDataSetChanged()
            var size = 0L
            list.forEach { size += it.length }
            val value = Utils.getSizeArray(size)
            binding.tvSize.text = value[0]
            binding.tvUnit.text = value[1]
            binding.ivEmpty.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
            binding.llBottom.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()
        binding.llTitle.ivBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.llSelectAll.setOnClickListener {
            isSelectAll = !isSelectAll
            list.forEach { it.isSelected = isSelectAll }
            adapter.notifyDataSetChanged()
            updateSelection()
        }
        binding.tvDelete.setOnClickListener {
            if (total <= 0) return@setOnClickListener
            val dialog = ConfirmDialog(this)
            dialog.action = {
                AdsMgr.showInsert(this, showCallBack = object : AdsShowCallBack() {
                    override fun next() {
                        cleanFileBeans(selectedFiles)
                        CleanResultActivity.total = total
                        CleanResultActivity.functionKey = SCREENSHOT_CLEAN
                        CleanResultActivity.titleName = getString(R.string.screenshot_clean)
                        goToAc(CleanResultActivity::class.java)
                    }

                })
            }
            dialog.showDialog("delete")
        }
    }
}