package storytelleric.broccoliic

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.LARGE_FILE_CLEAN
import tooic.fatalityic.corroborateic.Voluminousic
import autonomyic.polemicalic.congestionic.Unwindic
import autonomyic.polemicalic.congestionic.NASAic
import com.easy.clean.databinding.IndicationicBinding
import com.easy.clean.databinding.MacroicBinding
import com.easy.clean.databinding.VainlyicBinding
import intellectuallyic.jitteryic.mosaicic.Tailspinic
import rememberic.Stringsic
import tooic.fatalityic.redic.speckledic.hankeringic.Lilacic
import tooic.fatalityic.redic.speckledic.hankeringic.Townhouseic
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.util.Calendar


class Secretiveic : Reinstateic<IndicationicBinding>(IndicationicBinding::inflate) {

    private val LARGE_FILE_SIZE: Long = 1024 * 1024 * 10
    private val typeList by lazy {
        listOf(
            Voluminousic(getString(R.string.vociferouslyic), isSelected = true),
            Voluminousic(getString(R.string.comparableic)),
            Voluminousic(getString(R.string.platedic)),
            Voluminousic(getString(R.string.eweic)),
            Voluminousic(getString(R.string.clearic)),
            Voluminousic(getString(R.string.GEDic)),
            Voluminousic(getString(R.string.treacheryic)),
        )
    }

    private val sizeList by lazy {
        listOf(
            Voluminousic(getString(R.string.inclinedic), isSelected = true),
            Voluminousic(getString(R.string.satireic)),
            Voluminousic(getString(R.string.injunctionic)),
            Voluminousic(getString(R.string.crypticic)),
            Voluminousic(getString(R.string.puttyic)),
        )
    }

    private val timeList by lazy {
        listOf(
            Voluminousic(getString(R.string.interfereic), isSelected = true),
            Voluminousic(getString(R.string.cheerfulnessic)),
            Voluminousic(getString(R.string.untiringic)),
            Voluminousic(getString(R.string.glowinglyic)),
            Voluminousic(getString(R.string.headstrongic)),
            Voluminousic(getString(R.string.inflationaryic)),
        )
    }

    private var typePosition = 0
    private var sizePosition = 0
    private var timePosition = 0
    private var total: Long = 0
    private var allData = mutableListOf<Voluminousic>()
    private var list = mutableListOf<Voluminousic>()
    private val adapter by lazy {
        class ViewHolder(val binding: MacroicBinding) : RecyclerView.ViewHolder(binding.root)

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val binding = MacroicBinding.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]
                holder.binding.salveic.isVisible = Townhouseic.isVideo(item.mineType)
                if (Townhouseic.isImage(item.mineType) || Townhouseic.isVideo(item.mineType)) {
                    val round = resources.getDimensionPixelSize(R.dimen.consumeric)
                    val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
                    Glide.with(holder.itemView.context)
                        .load(item.path)
                        .apply(options)
                        .into(holder.binding.slutic)
                } else if (Townhouseic.isAudio(item.mineType)) {
                    holder.binding.slutic.setImageResource(R.drawable.scoutic)
                } else if (Townhouseic.isApk(item.mineType)) {
                    holder.binding.slutic.setImageResource(R.drawable.nightlifeic)
                } else if (Townhouseic.isDoc(item.mineType)) {
                    holder.binding.slutic.setImageResource(R.drawable.outplacementic)
                } else {
                    holder.binding.slutic.setImageResource(R.drawable.leaningic)
                }

                holder.binding.consequentic.text = item.name
                holder.binding.unzipic.text = Devastatingic.getSizeFormat(item.length)
                holder.binding.celibateic.isSelected = item.isSelected
                holder.binding.embitteric.visibility = if (position == itemCount - 1) View.GONE else View.VISIBLE
                holder.itemView.setOnClickListener {
                    item.isSelected = !item.isSelected
                    notifyItemChanged(position)
                    updateView()
                }
            }
        }
    }

    private var tabType = 0
    private val tabList = mutableListOf<Voluminousic>()
    private val tabAdapter by lazy {
        class ViewHolder(val binding: VainlyicBinding) : RecyclerView.ViewHolder(binding.root)

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

            override fun getItemCount(): Int = tabList.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = tabList[position]
                holder.binding.consequentic.text = item.name
                holder.binding.consequentic.setTextColor(getColor(if (item.isSelected) R.color.robic else R.color.efficiencyic))
                holder.binding.embitteric.visibility = if (position == itemCount - 1) View.GONE else View.VISIBLE
                holder.binding.celibateic.isSelected = item.isSelected
                holder.itemView.setOnClickListener {
                    tabList.forEach { it.isSelected = false }
                    item.isSelected = !item.isSelected
                    handleTab(item, position)
                }
            }
        }
    }

    private fun updateView() {
        total = list.filter { it.isSelected }.sumOf { it.length }
        setTextSize(binding.gownic, getString(R.string.involvedic), total)
        binding.gownic.isEnabled = total > 0
    }

    private fun handleTab(item: Voluminousic, position: Int) {
        binding.allegoricalic.visibility = View.GONE
        var textView: AppCompatTextView = binding.chowderic
        when (tabType) {
            1 -> {
                textView = binding.bimboic
                typePosition = position
            }

            2 -> {
                textView = binding.prospectic
                sizePosition = position
            }

            3 -> {
                textView = binding.chowderic
                timePosition = position
            }
        }
        textView.text = item.name
        binding.gownic.text = getString(R.string.involvedic)
        filterData()
        clearTab()
    }

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

    @SuppressLint("NotifyDataSetChanged")
    private fun filterData() {
        allData.forEach { it.isSelected = false }
        var data = filterType(allData, typePosition)
        data = filterSize(data, sizePosition)
        data = filterTime(data, timePosition)
        list = data.toMutableList()
        adapter.notifyDataSetChanged()
        binding.grippingic.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
        binding.herselfic.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
        binding.fingerprintic.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
        binding.gownic.visibility = if (list.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun filterType(list: List<Voluminousic>, position: Int): List<Voluminousic> {
        return when (position) {
            1 -> list.filter { Townhouseic.isImage(it.mineType) }
            2 -> list.filter { Townhouseic.isVideo(it.mineType) }
            3 -> list.filter { Townhouseic.isAudio(it.mineType) }
            4 -> list.filter { Townhouseic.isDoc(it.mineType) }
            5 -> list.filter { Townhouseic.isApk(it.mineType) }
            6 -> list.filterNot { file ->
                Townhouseic.mineTypes.any { mimeType -> file.mineType.startsWith(mimeType) }
            }

            else -> {
                list
            }
        }
    }

    private fun filterSize(list: List<Voluminousic>, position: Int): List<Voluminousic> {
        return when (position) {
            1 -> list.filter { it.length >= LARGE_FILE_SIZE * 2 }
            2 -> list.filter { it.length >= LARGE_FILE_SIZE * 5 }
            3 -> list.filter { it.length >= LARGE_FILE_SIZE * 10 }
            4 -> list.filter { it.length >= LARGE_FILE_SIZE * 50 }
            else -> {
                list.filter { it.length >= LARGE_FILE_SIZE }
            }
        }
    }


    private fun filterTime(list: List<Voluminousic>, position: Int): List<Voluminousic> {
        return when (position) {
            1 -> list.filter { it.lastModified > Calendar.getInstance().apply { add(Calendar.WEEK_OF_YEAR, -1) }.timeInMillis }
            2 -> list.filter { it.lastModified > Calendar.getInstance().apply { add(Calendar.MONTH, -1) }.timeInMillis }
            3 -> list.filter { it.lastModified > Calendar.getInstance().apply { add(Calendar.MONTH, -3) }.timeInMillis }
            4 -> list.filter { it.lastModified > Calendar.getInstance().apply { add(Calendar.MONTH, -6) }.timeInMillis }
            5 -> list.filter { it.lastModified > Calendar.getInstance().apply { add(Calendar.YEAR, -1) }.timeInMillis }
            else -> {
                list
            }
        }
    }

    private fun clearTab() {
        binding.insurgencyic.setBackgroundResource(R.color.generouslyic)
        binding.gownic.isEnabled = false
        binding.regenerationic.setBackgroundResource(R.drawable.consumptionic)
        binding.lyricsic.setBackgroundResource(R.drawable.consumptionic)
        binding.fourthlyic.setBackgroundResource(R.drawable.consumptionic)
        binding.symmetricallyic.isSelected = false
        binding.trainic.isSelected = false
        binding.iotaic.isSelected = false
        binding.bimboic.setTextColor(getColor(R.color.manuallyic))
        binding.prospectic.setTextColor(getColor(R.color.manuallyic))
        binding.chowderic.setTextColor(getColor(R.color.manuallyic))
        binding.pollinateic.setImageResource(R.drawable.developic)
        binding.proficientic.setImageResource(R.drawable.developic)
        binding.controversyic.setImageResource(R.drawable.developic)
        binding.regenerationic.isSelected = false
        binding.lyricsic.isSelected = false
        binding.fourthlyic.isSelected = false
    }


    private fun setTab(
        view: View,
        textView: AppCompatTextView,
        imageView: AppCompatImageView
    ) {
        if (view.isSelected) {
            hiddenTab()
            return
        }
        clearTab()
        view.isSelected = true
        view.setBackgroundResource(R.drawable.meringueic)
        imageView.setImageResource(R.drawable.relationshipic)
        textView.setTextColor(getColor(R.color.roadsideic))
        binding.insurgencyic.setBackgroundResource(R.color.roadsideic)
        when (view) {
            binding.regenerationic -> {
                binding.symmetricallyic.isSelected = true
                binding.lifestyleic.visibility = View.GONE
                showTab(1, typeList)
            }

            binding.lyricsic -> {
                binding.trainic.isSelected = true
                binding.lifestyleic.text = getString(R.string.cautiousic)
                binding.lifestyleic.visibility = View.VISIBLE
                showTab(2, sizeList)
            }

            binding.fourthlyic -> {
                binding.iotaic.isSelected = true
                binding.lifestyleic.text = getString(R.string.treacheryic)
                binding.lifestyleic.visibility = View.VISIBLE
                showTab(3, timeList)
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun showTab(type: Int, list: List<Voluminousic>) {
        binding.allegoricalic.visibility = View.VISIBLE
        tabType = type
        tabList.clear()
        tabList.addAll(list)
        tabAdapter.notifyDataSetChanged()
    }

    private fun hiddenTab() {
        binding.allegoricalic.visibility = View.GONE
        binding.regenerationic.isSelected = false
        binding.lyricsic.isSelected = false
        binding.fourthlyic.isSelected = false
        clearTab()
    }

    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.sanitaryic)
        binding.anomalousic.adapter = tabAdapter
        binding.anomalousic.layoutManager = LinearLayoutManager(this)
        binding.grippingic.adapter = adapter
        binding.grippingic.layoutManager = LinearLayoutManager(this)
        initData()
        showAdAnimation(LottieEnum.LARGE_FILE_LOTTIE) {
            Unwindic.showNative(binding.protectic, R.layout.explanatoryic)
        }
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            allData = async { Lilacic.findFiles(this@Secretiveic, LARGE_FILE_SIZE) }.await()
            launch(Dispatchers.Main) { filterData() }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.squaloric.telecommutingic.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.regenerationic.setOnClickListener {
            setTab(it, binding.bimboic, binding.pollinateic)
        }
        binding.lyricsic.setOnClickListener {
            setTab(it, binding.prospectic, binding.proficientic)
        }
        binding.fourthlyic.setOnClickListener {
            setTab(it, binding.chowderic, binding.controversyic)
        }
        binding.allegoricalic.setOnClickListener {
            hiddenTab()
        }
        binding.gownic.setOnClickListener {
            if (total <= 0) return@setOnClickListener
            val dialog = Stringsic(this)
            dialog.action = {
                cleanFileBeans(list)
                Unwindic.showInsert(this, showCallBack = object : NASAic() {
                    override fun next() {
                        Tailspinic.functionKey = LARGE_FILE_CLEAN
                        Tailspinic.total = total
                        Tailspinic.titleName = getString(R.string.sanitaryic)
                        goToAc(Tailspinic::class.java)
                    }
                })
            }
            dialog.showDialog("delete")
        }
    }

}