package stayic.surprisingic

import android.annotation.SuppressLint
import android.view.LayoutInflater
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 com.easy.clean.R
import tooic.fatalityic.jittersic.Reinstateic
import tooic.fatalityic.jittersic.LottieEnum
import tooic.fatalityic.jittersic.cleanFileBeans
import tooic.fatalityic.corroborateic.Protegeic.Companion.SCREENSHOT_CLEAN
import tooic.fatalityic.corroborateic.Voluminousic
import autonomyic.polemicalic.congestionic.Unwindic
import autonomyic.polemicalic.congestionic.NASAic
import com.easy.clean.databinding.GuaranteeicBinding
import com.easy.clean.databinding.SweatyicBinding
import com.easy.clean.databinding.MaladyicBinding
import intellectuallyic.jitteryic.mosaicic.Tailspinic
import rememberic.Stringsic
import tooic.fatalityic.redic.speckledic.hankeringic.Lilacic
import tooic.fatalityic.redic.speckledic.hankeringic.Devastatingic
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 Thornic : Reinstateic<GuaranteeicBinding>(GuaranteeicBinding::inflate) {


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

    private val adapter by lazy {
        class ChildViewHolder(val binding: SweatyicBinding) : ExpandableAdapter.ViewHolder(binding.root)
        class GroupViewHolder(val binding: MaladyicBinding) : 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 = SweatyicBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
                return ChildViewHolder(binding)
            }

            override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
                val binding = MaladyicBinding.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.consequentic.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@Thornic.resources.getDimensionPixelSize(R.dimen.unboundedic)

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

                margin = this@Thornic.resources.getDimensionPixelSize(R.dimen.quotableic)
                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@Thornic.resources.getDimensionPixelSize(R.dimen.deepenic).toInt()
                val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
                Glide.with(holder.itemView.context)
                    .load(child.path)
                    .apply(options)
                    .into(holder.binding.weaponryic)
                holder.binding.prospectic.text = Devastatingic.getSizeFormat(child.length)
                holder.binding.celibateic.isSelected = child.isSelected
                holder.binding.songic.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.vestibuleic.isSelected = isSelectAll
        binding.gownic.isEnabled = isSelection
        if (total > 0) {
            binding.gownic.setTextColor(getColor(R.color.roadsideic))
            binding.gownic.text =
                "${getString(R.string.involvedic)} (${Devastatingic.getSizeFormat(total)})"
            binding.gownic.background = getDrawable(R.drawable.scrutinyic)
        } else {
            binding.gownic.setTextColor(getColor(R.color.manuallyic))
            binding.gownic.text = getString(R.string.involvedic)
            binding.gownic.background = getDrawable(R.drawable.billowic)
        }
    }

    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.overseeric.setPadding(0, systemBars.top, 0, 0)
            insets
        }
    }

    override fun initView() {
        super.initView()
        binding.squaloric.jobic.text=getString(R.string.tautic)
        binding.umpireic.adapter = adapter
        val gridLayoutManager = GridLayoutManager(this, 3)
        gridLayoutManager.spanSizeLookup = MediaImageSpanLookup(3, adapter)
        binding.umpireic.layoutManager = gridLayoutManager
        initData()

        showAdAnimation(LottieEnum.SCREENSHOT_LOTTIE) {
            Unwindic.showNative(binding.protectic, R.layout.explanatoryic)
        }
    }

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

    @SuppressLint("NotifyDataSetChanged")
    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            Lilacic.findScreenshotsFiles(this@Thornic) { total, result ->
                list = result
                val value = Devastatingic.getSizeArray(total)
                launch(Dispatchers.Main) {
                    updateSelection()
                    binding.prospectic.text = value[0]
                    binding.wharvesic.text = value[1]
                    adapter.expandAllGroup()
                    adapter.notifyDataSetChanged()
                    binding.herselfic.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
                    binding.fingerprintic.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
                    binding.counteric.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()
        binding.squaloric.telecommutingic.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.thereafteric.setOnClickListener {
            isSelectAll = !isSelectAll
            list.forEach { it.items.forEach { it.isSelected = isSelectAll } }
            adapter.notifyDataSetChanged()
            updateSelection()
        }
        binding.gownic.setOnClickListener {
            if (total <= 0) return@setOnClickListener
            val dialog = Stringsic(this)
            dialog.action = {
                Unwindic.showInsert(this, showCallBack = object : NASAic() {
                    override fun next() {
                        cleanFileBeans(selectedFiles)
                        Tailspinic.total = total
                        Tailspinic.functionKey = SCREENSHOT_CLEAN
                        Tailspinic.titleName = getString(R.string.tautic)
                        goToAc(Tailspinic::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
        }
    }
}