package com.simplecleaner.app.ui.screenshot

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.simplecleaner.app.R
import com.simplecleaner.app.base.BaseActivity
import com.simplecleaner.app.base.LottieEnum
import com.simplecleaner.app.base.cleanFileBeans
import com.simplecleaner.app.bean.FeatureBean.Companion.SCREENSHOT_CLEAN
import com.simplecleaner.app.bean.FileBean
import com.simplecleaner.app.business.ads.AdsMgr
import com.simplecleaner.app.business.ads.AdsShowCallBack
import com.simplecleaner.app.databinding.ActivityScreenshotCleanBinding
import com.simplecleaner.app.databinding.ItemScreenshotCleanChildBinding
import com.simplecleaner.app.databinding.ItemScreenshotCleanGroupBinding
import com.simplecleaner.app.ui.cleanresult.CleanResultActivity
import com.simplecleaner.app.ui.dialog.ConfirmDialog
import com.simplecleaner.app.utils.MediaUtils
import com.simplecleaner.app.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 pokercc.android.expandablerecyclerview.ExpandableAdapter

class ScreenshotCleanActivity : BaseActivity<ActivityScreenshotCleanBinding>(ActivityScreenshotCleanBinding::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 ChildViewHolder(val binding: ItemScreenshotCleanChildBinding) : ExpandableAdapter.ViewHolder(binding.root)
        class GroupViewHolder(val binding: ItemScreenshotCleanGroupBinding) : ExpandableAdapter.ViewHolder(binding.root)

        object : ExpandableAdapter<ExpandableAdapter.ViewHolder>() {
            override fun getChildCount(groupPosition: Int): Int = list[groupPosition].items.size

            override fun getGroupCount(): Int = list.size

            override fun onCreateChildViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
                val binding = ItemScreenshotCleanChildBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
                return ChildViewHolder(binding)
            }

            override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
                val binding = ItemScreenshotCleanGroupBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
                return GroupViewHolder(binding)
            }

            override fun onGroupViewHolderExpandChange(
                holder: ViewHolder,
                groupPosition: Int,
                animDuration: Long,
                expand: Boolean
            ) {
            }

            override fun onBindGroupViewHolder(
                holder: ViewHolder,
                groupPosition: Int,
                expand: Boolean,
                payloads: List<Any>
            ) {
                holder as GroupViewHolder
                val group = list[groupPosition]
                holder.binding.tvName.text = group.name
                holder.itemView.setOnClickListener { }
            }

            override fun onBindChildViewHolder(
                holder: ViewHolder,
                groupPosition: Int,
                childPosition: Int,
                payloads: List<Any>
            ) {
                holder as ChildViewHolder
                val child = list[groupPosition].items[childPosition]
                val width = resources.displayMetrics.widthPixels
                var margin = this@ScreenshotCleanActivity.resources.getDimensionPixelSize(R.dimen.dp_45)

                val imageWidth = (width - margin) / 3
                holder.binding.ivImage.layoutParams.width = imageWidth
                holder.binding.ivImage.layoutParams.height = imageWidth

                margin = this@ScreenshotCleanActivity.resources.getDimensionPixelSize(R.dimen.dp_15)
                if (childPosition % 3 == 0) {
                    holder.itemView.setPadding(margin, 0, 0, 0)
                } else if (childPosition % 3 == 2) {
                    holder.itemView.setPadding(0, 0, margin, 0)
                } else {
                    holder.itemView.setPadding(margin / 2, 0, margin / 2, 0)
                }
                val round = this@ScreenshotCleanActivity.resources.getDimensionPixelSize(R.dimen.dp_8).toInt()
                val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
                Glide.with(holder.itemView.context)
                    .load(child.path)
                    .apply(options)
                    .into(holder.binding.ivImage)
                holder.binding.tvSize.text = Utils.getSizeFormat(child.length)
                holder.binding.ivSelect.isSelected = child.isSelected
                holder.binding.clContainer.setOnClickListener {
                    child.isSelected = !child.isSelected
                    notifyChildChange(groupPosition, childPosition)
                    updateSelection()
                }
            }
        }
    }

    private fun updateSelection() {
        selectedFiles = list.flatMap { it.items.takeIf { it.isNotEmpty() }?.filter { it.isSelected } ?: emptyList() }
        total = selectedFiles.sumOf { it.length }
        updateView(selectedFiles.isNotEmpty())
    }

    private fun updateView(isSelection: Boolean) {

        binding.ivSelectAll.isSelected = isSelectAll
        binding.tvDelete.isEnabled = isSelection

        setTextSize(binding.tvDelete, getString(R.string.delete), total)
    }

    fun setTextSize(view: TextView, content: String, total: Long) {
        view.text = if (total > 0) "$content (${Utils.getSizeFormat(total)})" else content
    }

    override fun useDefaultImmersive() {
        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)
        gridLayoutManager.spanSizeLookup = MediaImageSpanLookup(3, adapter)
        binding.expandableFiles.layoutManager = gridLayoutManager
        initData()

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

    override fun handleBackCallBack() {
        super.handleBackCallBack()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            MediaUtils.findScreenshotsFiles(this@ScreenshotCleanActivity) { total, result ->
                list = result
                val value = Utils.getSizeArray(total)
                launch(Dispatchers.Main) {
                    updateSelection()
                    binding.tvSize.text = value[0]
                    binding.tvUnit.text = value[1]
                    adapter.expandAllGroup()
                    adapter.notifyDataSetChanged()
                    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.ivBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.llSelectAll.setOnClickListener {
            isSelectAll = !isSelectAll
            list.forEach { it.items.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")
        }
    }

    internal class MediaImageSpanLookup(
        private val spanCount: Int,
        private val expandableAdapter: ExpandableAdapter<*>
    ) :
        GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            val viewType = expandableAdapter.getItemViewType(position)
            return if (expandableAdapter.isGroup(viewType)) spanCount else 1
        }
    }

}