package startic.perkic.chemistic

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.easy.clean.R
import tooic.fatalityic.jittersic.Reinstateic
import tooic.fatalityic.jittersic.LottieEnum
import tooic.fatalityic.corroborateic.Protegeic.Companion.SIMILAR_PHOTOS
import tooic.fatalityic.corroborateic.Predominateic
import autonomyic.polemicalic.congestionic.Unwindic
import autonomyic.polemicalic.congestionic.NASAic
import com.easy.clean.databinding.MousyicBinding
import com.easy.clean.databinding.ShowmanicBinding
import com.easy.clean.databinding.CogenticBinding
import intellectuallyic.jitteryic.mosaicic.Tailspinic
import rememberic.Stringsic
import negligentlyic.wrongic.bottomic.Timidic
import tooic.fatalityic.redic.speckledic.hankeringic.Incomparableic
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.async
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.Semaphore

class Shadyic : Reinstateic<MousyicBinding>(MousyicBinding::inflate) {

    private val semaphore = Semaphore(20)
    private var state = 0
    private var list = mutableListOf<Predominateic>()
    private var selectedFiles = listOf<Predominateic>()
    private var total: Long = 0


    private val adapter by lazy {
        class ViewHolder(val binding: ShowmanicBinding) : RecyclerView.ViewHolder(binding.root)

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

            override fun getItemCount(): Int = list.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = list[position]
                val total = item.items.filter { it.isSelect }.sumOf { it.size }
                holder.binding.prospectic.text = Devastatingic.getSizeFormat(total)
                holder.binding.celibateic.isSelected = item.items[0].isSelect

                val width = resources.displayMetrics.widthPixels
                val margin = resources.getDimensionPixelSize(R.dimen.unboundedic)
                val imageWidth = (width - margin) / 4
                val largePhotoWidth = imageWidth * 2
                val largePhotoHeight = (largePhotoWidth * 0.92).toInt()
                holder.binding.transposeic.layoutParams.width = largePhotoWidth
                holder.binding.transposeic.layoutParams.height = largePhotoHeight

                val round = resources.getDimensionPixelSize(R.dimen.deepenic)
                val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
                Glide.with(holder.itemView.context)
                    .load(item.items[0].url)
                    .override(largePhotoWidth, largePhotoHeight)
                    .apply(options)
                    .into(holder.binding.transposeic)
                holder.binding.transposeic.setOnClickListener {
                    item.items[0].isSelect = !item.items[0].isSelect
                    holder.binding.celibateic.isSelected = item.items[0].isSelect
                    updateView(holder, item)
                }

                val largePhotos = item.items.take(5)
                val largeAdapter = SimilarPhotosChildAdapter(largePhotos.subList(1, largePhotos.size)) {
                    updateView(holder, item)
                }
                holder.binding.involvementic.layoutManager =
                    GridLayoutManager(this@Shadyic, 2, GridLayoutManager.VERTICAL, false)
                holder.binding.involvementic.adapter = largeAdapter

                val photos = if (item.items.size > 4) item.items.subList(5, item.items.size) else mutableListOf()
                val adapter = SimilarPhotosChildAdapter(photos) { updateView(holder, item) }
                holder.binding.concaveic.layoutManager =
                    GridLayoutManager(this@Shadyic, 4, GridLayoutManager.VERTICAL, false)
                holder.binding.concaveic.adapter = adapter
            }

            private fun updateView(holder: ViewHolder, item: Predominateic) {
                val total = item.items.filter { it.isSelect }.sumOf { it.size }
                holder.binding.prospectic.text = Devastatingic.getSizeFormat(total)
                updateSelection()
            }
        }
    }

    inner class SimilarPhotosChildAdapter(
        var list: List<Predominateic>,
        private val block: () -> Unit
    ) : RecyclerView.Adapter<SimilarPhotosChildAdapter.ViewHolder>() {
        inner class ViewHolder(val binding: CogenticBinding) : RecyclerView.ViewHolder(binding.root)

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): ViewHolder {
            val binding = CogenticBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            return ViewHolder(binding)
        }

        override fun getItemCount(): Int = list.size

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = list[position]
            val width = holder.itemView.context.resources.displayMetrics.widthPixels
            val context = holder.itemView.context
            val margin = context.resources.getDimensionPixelSize(R.dimen.unboundedic)
            val imageWidth = (width - margin) / 4
            val imageHeight = (imageWidth * 0.91).toInt()
            holder.binding.packeric.layoutParams.width = imageWidth
            holder.binding.packeric.layoutParams.height = imageHeight
            holder.binding.celibateic.isSelected = item.isSelect
            holder.itemView.setOnClickListener {
                item.isSelect = !item.isSelect
                notifyItemChanged(position)
                block.invoke()
                updateSelection()
            }

            val round = context.resources.getDimensionPixelSize(R.dimen.deepenic)
            val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
            Glide.with(holder.itemView.context)
                .load(item.url)
                .override(imageWidth, imageHeight)
                .apply(options)
                .into(holder.binding.packeric)
        }
    }

    private fun updateSelection() {
        selectedFiles = list.flatMap { it.items.takeIf { it.isNotEmpty() }?.filter { it.isSelect } ?: emptyList() }
        total = selectedFiles.sumOf { it.size }
        showSelection(total > 0)
    }

    private fun showSelection(isSelection: Boolean) {
        binding.gownic.isEnabled = isSelection
        setTextSize(binding.gownic, getString(R.string.involvedic), total)
    }

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


    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.conjectureic)
        binding.concaveic.adapter = adapter
        binding.concaveic.layoutManager = LinearLayoutManager(this)
        initData()
        showAdAnimation(LottieEnum.SIMILAR_PHOTOS_LOTTIE) {
            if (state != 0) scanComplete()
            state = 1

            Unwindic.showNative(binding.protectic, R.layout.explanatoryic)
        }
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val images = Lilacic.findImageFiles(this@Shadyic)
            val similarBeans = images.mapNotNull { value ->
                lifecycleScope.async(Dispatchers.IO) {
                    semaphore.acquire() // 请求许可
                    try {
                        Allergyic.createImage(value.path)
                    } finally {
                        semaphore.release() // 释放许可
                    }
                }.await()
            }
            val hasSame = mutableSetOf<String>()
            similarBeans.forEach { similar ->
                if (hasSame.contains(similar.url)) return@forEach
                hasSame.add(similar.url)
                similar.items.add(similar)
                similarBeans.forEach {
                    if (!hasSame.contains(it.url) && Allergyic.similarCondition(similar, it)) {
                        hasSame.add(it.url)
                        similar.items.add(it)
                    }
                }
            }
            list = similarBeans.filter { it.items.size > 1 }.toMutableList()
            launch(Dispatchers.Main) {
                if (state != 0) scanComplete()
                state = 2
            }
        }
    }

    private fun scanComplete() {
        binding.root.postDelayed({
            setSelectAll(true)
            stopAnimation()
        }, 2500)
    }

    fun stopAnimation() {
        val lottie: LottieAnimationView? = findViewById(R.id.Europeanic)
        lottie?.clearAnimation()
        findViewById<View?>(R.id.Allahic)?.visibility = View.GONE
        isBackDisable = false
    }

    override fun initListener() {
        super.initListener()

        binding.squaloric.telecommutingic.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.celibateic.setOnClickListener {
            it.isSelected = !it.isSelected
            setSelectAll(it.isSelected)
        }
        binding.gownic.setOnClickListener {
            if (selectedFiles.isEmpty()) return@setOnClickListener
            val dialog = Stringsic(this)
            dialog.action = {
                Unwindic.showInsert(this, showCallBack = object : NASAic() {
                    override fun next() {
                        cleanSimilarBeans(selectedFiles)
                        Tailspinic.total = total
                        Tailspinic.functionKey = SIMILAR_PHOTOS
                        Tailspinic.titleName = getString(R.string.conjectureic)
                        goToAc(Tailspinic::class.java)
                    }
                })
            }
            dialog.showDialog("delete")
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setSelectAll(isSelected: Boolean) {
        binding.celibateic.isSelected = isSelected
        list.forEach { similar ->
            similar.items.forEachIndexed { index, similarBean ->
                similarBean.isSelect = isSelected
                if (isSelected && index == 0) {
                    similarBean.isSelect = false
                }
            }
        }
        adapter.notifyDataSetChanged()
        binding.celibateic.setImageResource(if (isSelected) R.drawable.obligeic else R.drawable.copeic)
        updateSelection()
    }

    fun AppCompatActivity.cleanSimilarBeans(list: List<Predominateic>) {
        lifecycleScope.launch(Dispatchers.IO) {
            val paths = list.map { it.url }.toTypedArray()
            paths.forEach {
                Timidic.addRecycleBinFile(File(it))
                Incomparableic.deleteFile(it)
            }
            launch(Dispatchers.Main) { Lilacic.updateMedia(applicationContext, paths) }
        }
    }

}