package importantedto.deserveedto.manufactureredto.viableedto

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.EauxedtoBinding
import com.base.datarecovery.databinding.NoiseedtoBinding
import com.bumptech.glide.Glide
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatSize
import importantedto.concreteedto.cameedto.Absenceedto
import importantedto.concreteedto.cameedto.Changingedto
import importantedto.concreteedto.cameedto.Hateedto.SCAN_AUDIOS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_DOCUMENTS
import importantedto.maidedto.witnessedto.nationalismedto.Gestureedto.inflate
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

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

    private val beanList = arrayListOf<Changingedto>()
    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.eauxedto.inflate(parent))
    }

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

    override fun onBindViewHolder(holder: MCV, position: Int) {
        val binding = EauxedtoBinding.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.eatedto.text = time
        binding.countedto.isSelected = bean.isSelect


        val subAdapter = MediaColumnsAdapter()

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

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

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

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

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

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CS {
            var layout = when (columns) {
                2 -> R.layout.greatedto
                3 -> R.layout.identityedto
                4 -> R.layout.photographyedto
                else -> R.layout.greatedto
            }
            if ((scanType == SCAN_DOCUMENTS) || (scanType == SCAN_AUDIOS)) {
                layout = R.layout.noiseedto
            }
            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 = NoiseedtoBinding.bind(holder.itemView)
                    binding.countedto.isSelected = data.isSelect
                    val icon = when (data.type) {
                        "PDF" -> R.mipmap.bearedto
                        "DOC" -> R.mipmap.pleadedto
                        "XLS" -> R.mipmap.lazyedto
                        "PPT" -> R.mipmap.calorieedto
                        "MP3" -> R.mipmap.wheneveredto
                        "WAV" -> R.mipmap.measureedto
                        "FLAC" -> R.mipmap.motoristedto
                        else -> 0
                    }
                    binding.armedto.setImageResource(icon)
                    val file = File(data.path)
                    binding.anotheredto.text = file.name
                    val time = SimpleDateFormat("MMM-dd-yyyy", Locale.getDefault()).format(file.lastModified())
                    val size = file.length().toFormatSize()
                    val info = "$time $size"
                    binding.nameedto.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<Absenceedto>) {
            list.clear()
            list.addAll(bean)
            notifyDataSetChanged()
        }

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


    }

    @SuppressLint("NotifyDataSetChanged")
    fun subItemClick(data: Absenceedto) {
        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<Absenceedto> {
        return beanList.flatMap { it.recoveryList }.filter { it.isSelect }
    }
}