package importantedto.deserveedto.manufactureredto.viableedto

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.core.view.isVisible
import com.base.datarecovery.R
import com.base.datarecovery.databinding.AnywhereedtoBinding
import com.base.datarecovery.databinding.FlavoredtoBinding
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatSize
import importantedto.concreteedto.cameedto.ChildBean
import importantedto.concreteedto.cameedto.Unpleasantedto
import importantedto.gallonedto.Tumbleedto
import pokercc.android.expandablerecyclerview.ExpandableAdapter

class Wayedto(private val chooseAction: (size: Long) -> Unit) : ExpandableAdapter<ExpandableAdapter.ViewHolder>() {

    private val TAG = "JunkExpandAdapter"

    private val parentBeanList by lazy {
        mutableListOf(
            Unpleasantedto(
                title = "Residual file",
                isParentSelected = true,
                expanded = false
            ),
            Unpleasantedto(
                title = "Useless installation package",
                isParentSelected = true,
                expanded = false
            ),
            Unpleasantedto(
                title = "Temp File",
                isParentSelected = true,
                expanded = false
            ),
            Unpleasantedto(
                title = "Log File",
                isParentSelected = true,
                expanded = false
            )
        )
    }
    var animators = mutableMapOf<Int, ValueAnimator>()

    inner class ChildViewHolder(val binding: FlavoredtoBinding) : ViewHolder(binding.root)

    inner class ParentViewHolder(val binding: AnywhereedtoBinding) : ViewHolder(binding.root)

    override fun getChildCount(groupPosition: Int): Int {
        return parentBeanList[groupPosition].childItem.size
    }

    override fun getGroupCount(): Int {
        return parentBeanList.size
    }

    override fun onCreateChildViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = FlavoredtoBinding.inflate(inflater, viewGroup, false)
        return ChildViewHolder(binding)
    }

    override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(viewGroup.context)
        val binding = AnywhereedtoBinding.inflate(inflater, viewGroup, false)
        return ParentViewHolder(binding)
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onBindGroupViewHolder(holder: ViewHolder, groupPosition: Int, expand: Boolean, payloads: List<Any>) {
        val viewHolder = holder as? ParentViewHolder ?: return
        val parentBean = parentBeanList[groupPosition]

        viewHolder.binding.salespersonedto.text = parentBean.title
        parentBean.expanded = expand

        if (parentBean.expanded) {
            viewHolder.binding.anxietyedto.setImageResource(R.mipmap.electronedto)
        } else {
            viewHolder.binding.anxietyedto.setImageResource(R.mipmap.performeredto)
        }
        if (parentBean.title == "Residual file") {
            viewHolder.binding.appointedto.text = parentBean.childItem.size.toString() + " items"
        } else {
            viewHolder.binding.appointedto.text = parentBean.parentSize.toFormatSize(1)
        }

        viewHolder.binding.anxietyedto.isVisible = true
        viewHolder.binding.cooledto.isSelected = parentBean.isParentSelected

        bindParentAnimation(parentBean, groupPosition, viewHolder)

        if (parentBean.childItem.isEmpty()) {
            viewHolder.binding.cooledto.setOnClickListener { }
        } else {
            viewHolder.binding.cooledto.setOnClickListener {
                viewHolder.binding.cooledto.isSelected = !viewHolder.binding.cooledto.isSelected
                parentBean.isParentSelected = viewHolder.binding.cooledto.isSelected

                parentBean.childItem.forEach {
                    it.isChildSelected = parentBean.isParentSelected
                }
                notifyDataSetChanged()

                chooseSizeChange()
            }
        }

    }

    override fun onGroupViewHolderExpandChange(holder: ViewHolder, groupPosition: Int, animDuration: Long, expand: Boolean) {}

    private fun chooseSizeChange() {
        val selectSize = parentBeanList.sumOf { it.childItem.filter { it.isChildSelected }.sumOf { it.childSize } }
        chooseAction.invoke(selectSize)
    }

    fun getChoosePath(): List<ChildBean> {
        return parentBeanList.flatMap { it.childItem }.filter { it.isChildSelected }
    }

    fun getAllChildItemCount(): Int {
        return parentBeanList.flatMap { it.childItem }.size
    }

    private fun bindParentAnimation(parentBean: Unpleasantedto, groupPosition: Int, viewHolder: ParentViewHolder) {
        if (parentBean.isfinish) {
            viewHolder.binding.mainedto.isVisible = false
            viewHolder.binding.cooledto.isVisible = true
            animators[groupPosition]?.cancel()
        } else {
            Tumbleedto.logDebug(TAG, "play parent ValueAnimator")
            animators[groupPosition] ?: ValueAnimator.ofFloat(0f, 360f).apply {
                duration = 1000
                repeatMode = ValueAnimator.RESTART
                repeatCount = ValueAnimator.INFINITE
                interpolator = LinearInterpolator()
                addUpdateListener {
                    viewHolder.binding.mainedto.rotation = it.animatedValue as Float
                }
                start()
                animators[groupPosition] = this
            }
            viewHolder.binding.mainedto.isVisible = true
            viewHolder.binding.cooledto.isVisible = false
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onBindChildViewHolder(holder: ViewHolder, groupPosition: Int, childPosition: Int, payloads: List<Any>) {
        val viewHolder = holder as? ChildViewHolder ?: return
        val childBean = parentBeanList[groupPosition].childItem[childPosition]
        val parentBean = parentBeanList[groupPosition]
        val context = holder.itemView.context

        viewHolder.binding.partedto.text = childBean.childname
        viewHolder.binding.portionedto.isSelected = childBean.isChildSelected
        viewHolder.binding.hypothesizeedto.text = childBean.childSize.toFormatSize()

        when (groupPosition) {
            0 -> {
                holder.binding.behaveedto.setImageResource(R.mipmap.ventureedto)
                viewHolder.binding.partedto.text = childBean.chilepath
            }

            1 -> {
                try {
                    val apkFilePath = childBean.chilepath // 替换成您的APK文件路径
                    val packageInfo =
                        context.packageManager.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES)
                    if (packageInfo != null) {
                        val applicationInfo = packageInfo.applicationInfo
                        val appIcon: Drawable = context.packageManager.getApplicationIcon(applicationInfo)
                        viewHolder.binding.behaveedto.setImageDrawable(appIcon)
                    } else {
                        holder.binding.behaveedto.setImageResource(R.mipmap.linearedto)
                    }
                } catch (e: Exception) {
                    holder.binding.behaveedto.setImageResource(R.mipmap.linearedto)
                }
            }

            2 -> {
                holder.binding.behaveedto.setImageResource(R.mipmap.rootedto)
            }

            3 -> {
                holder.binding.behaveedto.setImageResource(R.mipmap.strapedto)
            }
        }


        viewHolder.itemView.setOnClickListener {
            viewHolder.binding.portionedto.isSelected = !viewHolder.binding.portionedto.isSelected
            childBean.isChildSelected = viewHolder.binding.portionedto.isSelected
            parentBean.isParentSelected = parentBean.childItem.all { it.isChildSelected }
            notifyDataSetChanged()
            chooseSizeChange()
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    fun addChildData(position: Int, childBeanList: List<ChildBean>) {
        val parentBean = parentBeanList[position]
        parentBean.isfinish = true
        parentBean.isParentSelected = true
        parentBean.childItem.addAll(childBeanList)
        parentBean.parentSize = childBeanList.sumOf { it.childSize }
        Tumbleedto.logDebug(TAG, "addChildData parentBean=$parentBean")
        notifyDataSetChanged()
        chooseSizeChange()
    }

}