package rallyedto.dumpedto.editionedto

import android.annotation.SuppressLint
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.datarecovery.R
import com.base.datarecovery.databinding.ArtedtoBinding
import com.base.datarecovery.databinding.CommunistedtoBinding
import com.bumptech.glide.Glide
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatSize
import rallyedto.farewelledto.Strategicedto.inflate
import rallyedto.policeedto.huntedto.Desertedto
import rallyedto.policeedto.huntedto.Mediumedto
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_AUDIOS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_DOCUMENTS
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class Toothedto(
    val scanType: Int,
    val select: (all: Boolean, size: Int) -> Unit,
) : RecyclerView.Adapter<Toothedto.MCV>() {

    private val beanList = arrayListOf<Mediumedto>()
    private var hideThumbnails: Boolean = false
    private var columns: Int = 2

    class MCV(view: View) : ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MCV {
        return MCV(R.layout.artedto.inflate(parent))
    }

    override fun getItemCount(): Int {
        return beanList.size
    }

    override fun onBindViewHolder(holder: MCV, position: Int) {
        val binding = ArtedtoBinding.bind(holder.itemView)
        val context = holder.itemView.context
        val bean = beanList[position]
        val file = File(bean.recoveryList.first().path)
        val time = SimpleDateFormat("yyyy-MMM-dd", Locale.getDefault()).format(file.lastModified())
        binding.beautyedto.text = time
        binding.auntedto.isSelected = bean.isSelect


        val subAdapter = MediaColumnsAdapter()

        if (scanType == SCAN_DOCUMENTS || scanType == SCAN_AUDIOS) {
            binding.formedto.layoutManager = LinearLayoutManager(context)
        } else {
            binding.formedto.layoutManager = GridLayoutManager(context, columns)
            binding.formedto.layoutParams =
                LinearLayout.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT).apply {
                    topMargin = context.resources.getDimensionPixelOffset(R.dimen.exemptedto)
                    gravity = Gravity.CENTER_HORIZONTAL
                }
        }
        binding.formedto.adapter = subAdapter
        val list = if (hideThumbnails) bean.recoveryList.filter { !it.isThumbnails } else bean.recoveryList
        if (list.isEmpty()) {
            binding.innocentedto.visibility = View.GONE
        } else {
            binding.innocentedto.visibility = View.VISIBLE
            subAdapter.setData(list)
        }

        binding.auntedto.setOnClickListener {
            bean.isSelect = !bean.isSelect
            binding.auntedto.isSelected = bean.isSelect
            notifyItemChanged(position)
            itemClick(bean.isSelect, subAdapter)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: List<Mediumedto>) {
        beanList.clear()
        beanList.addAll(data)
        notifyDataSetChanged()
    }

    inner class MediaColumnsAdapter : RecyclerView.Adapter<MediaColumnsAdapter.CS>() {
        private val list = arrayListOf<Desertedto>()

        inner class CS(view: View) : ViewHolder(view) {
            val iv = view.findViewById<ImageView>(R.id.usefuledto)
            val ivSelector = view.findViewById<ImageView>(R.id.auntedto)
            val tvSize = view.findViewById<TextView>(R.id.startedto)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CS {
            var layout = when (columns) {
                2 -> R.layout.glimpseedto
                3 -> R.layout.differenceedto
                4 -> R.layout.replacementedto
                else -> R.layout.glimpseedto
            }
            if ((scanType == SCAN_DOCUMENTS) || (scanType == SCAN_AUDIOS)) {
                layout = R.layout.communistedto
            }
            return CS(layout.inflate(parent))
        }

        override fun getItemCount(): Int {
            return list.size
        }

        override fun onBindViewHolder(holder: CS, position: Int) {
        }

        override fun onBindViewHolder(holder: CS, position: Int, payloads: MutableList<Any>) {

            val context = holder.itemView.context
            val data = list[position]

            if ((scanType == SCAN_DOCUMENTS) or (scanType == SCAN_AUDIOS)) {
                if (payloads.isEmpty()) {
                    val binding = CommunistedtoBinding.bind(holder.itemView)
                    binding.auntedto.isSelected = data.isSelect
                    val icon = when (data.type) {
                        "PDF" -> R.mipmap.verdictedto
                        "DOC" -> R.mipmap.advocateedto
                        "XLS" -> R.mipmap.overedto
                        "PPT" -> R.mipmap.loudedto
                        "MP3" -> R.mipmap.nearlyedto
                        "WAV" -> R.mipmap.criticaledto
                        "FLAC" -> R.mipmap.inhabitantedto
                        else -> 0
                    }
                    binding.studiededto.setImageResource(icon)
                    val file = File(data.path)
                    binding.seasonedto.text = file.name
                    val time = SimpleDateFormat("MMM-dd-yyyy", Locale.getDefault()).format(file.lastModified())
                    val size = file.length().toFormatSize()
                    val info = "$time $size"
                    binding.takeedto.text = info
                    binding.root.setOnClickListener {
                        data.isSelect = !data.isSelect
                        holder.ivSelector.isSelected = data.isSelect
                        notifyItemChanged(position, "asdada")
                        subItemClick(data)
                    }
                } else {
                    holder.ivSelector.isSelected = data.isSelect
                    super.onBindViewHolder(holder, position, payloads)
                }

            } else {
                if (payloads.isEmpty()) {
                    Glide.with(context).asBitmap().load(data.path).centerCrop().into(holder.iv)
                    holder.ivSelector.isSelected = data.isSelect
                    holder.itemView.setOnClickListener {
                        data.isSelect = !data.isSelect
                        holder.ivSelector.isSelected = data.isSelect
                        notifyItemChanged(position, "changeIv")

                        subItemClick(data)
                    }
                    val file = File(data.path)
                    holder.tvSize.text = file.length().toFormatSize()
                } else {
                    holder.ivSelector.isSelected = data.isSelect
                    super.onBindViewHolder(holder, position, payloads)
                }
            }

        }

        @SuppressLint("NotifyDataSetChanged")
        fun setData(bean: List<Desertedto>) {
            list.clear()
            list.addAll(bean)
            notifyDataSetChanged()
        }

        @SuppressLint("NotifyDataSetChanged")
        fun toggleSelect(select: Boolean) {
            list.forEach {
                it.isSelect = select
            }
            notifyDataSetChanged()
        }


    }

    @SuppressLint("NotifyDataSetChanged")
    fun subItemClick(data: Desertedto) {
        val folderBean = beanList.find { it.recoveryList.contains(data) }

        folderBean?.let { folder ->
            val select = folder.recoveryList.all { it.isSelect }
            if (folder.isSelect != select) {
                folder.isSelect = select
                notifyDataSetChanged()
            }
        }
        val all = beanList.all { it.isSelect }
        val size = beanList.sumOf { it.recoveryList.filter { bean -> bean.isSelect }.size }
        select.invoke(all, size)
    }

    private fun itemClick(isSelect: Boolean, subAdapter: MediaColumnsAdapter) {
        subAdapter.toggleSelect(isSelect)

        val all = beanList.all { it.isSelect }
        val size = beanList.sumOf { it.recoveryList.filter { bean -> bean.isSelect }.size }
        select.invoke(all, size)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun toggleThumbnails(hideThumbnails: Boolean) {
        this.hideThumbnails = hideThumbnails
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun toggleAllSelect(selected: Boolean) {
        beanList.forEach {
            it.isSelect = selected
            it.recoveryList.forEach { bean -> bean.isSelect = selected }
        }
        notifyDataSetChanged()
        val all = beanList.all { it.isSelect }
        val size = beanList.sumOf { it.recoveryList.filter { bean -> bean.isSelect }.size }
        select.invoke(all, size)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun changeColumns(columns: Int) {
        this.columns = columns
        notifyDataSetChanged()
    }

    fun getSelectData(): List<Desertedto> {
        return beanList.flatMap { it.recoveryList }.filter { it.isSelect }
    }
}