package com.base.datarecovery.activity.repeat

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.base.datarecovery.R
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.bean.ImageInfoBean
import com.base.datarecovery.databinding.ActivityDuplicateImageBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.help.PermissionHelp.requestStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.MediaStoreUtils
import com.base.datarecovery.utils.NewFileUtils
import com.base.datarecovery.utils.SimarPhotoUtils
import com.base.datarecovery.view.DialogViews.showDeletePermanentlyDialog
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import com.base.datarecovery.view.DialogViews.showGerPermission
import com.bumptech.glide.Glide


class SimilarPicAt : BaseActivity<ActivityDuplicateImageBinding>() {
    private var isSelectAll = false

    override val binding: ActivityDuplicateImageBinding by lazy {
        ActivityDuplicateImageBinding.inflate(layoutInflater)
    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        if (checkStorePermission()) {
            initData()
        } else {
            showGerPermission("Storage Permission Required",
                "This feature requires access to your storage to scan your files and clean up repeat photos. We will not transmit your data to any third-party service. Please grant permission so that we can provide you with better service.",
                deny = { finishToMain() },
                allow = {
                    requestStorePermission(launcher, result = {
                        if (it) {
                            initData()
                        } else {
                            finishToMain()
                        }
                    })
                })
        }
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        binding.idTvDelete.isEnabled = false

    }
    private fun initData(){
        binding.idLlResult.isVisible = true
        fileList = SimarPhotoUtils.similarImageList
        binding.idTvNoData.isVisible = fileList.size == 0
        binding.idTvDelete.isVisible = fileList.size > 0
        binding.idTvAll.isVisible = fileList.size > 0
        binding.idImgSelect.isVisible = fileList.size > 0
        initAdapter()
        if (fileList.size > 6) {
            AdmobMaxHelper.admobMaxShowNativeAd(this, binding.flAd, 1)
        }
    }
    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        binding.idBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showExitFunctionDialog {
                    if (it) {
                        AdmobMaxHelper.admobMaxShowInterstitialAd(this@SimilarPicAt, false) {
                            finishToMain()
                        }
                    } else {
                        finishToMain()
                    }

                }
            }
        })

        binding.idImgSelect.setOnClickListener {
            if (isSelectAll) {
                isSelectAll = false
                binding.idTvAll.text = "All"
                binding.idImgSelect.setImageResource(R.mipmap.weixuan)
            } else {
                isSelectAll = true
                binding.idTvAll.text = "Cancel"
                binding.idImgSelect.setImageResource(R.mipmap.xuanzhong)
            }
            fileList.forEach { it.isSelect = isSelectAll }
            // mAdapter.notifyItemRangeChanged(0, fileList.size, 1)
            binding.idRlList.adapter?.notifyItemRangeChanged(0, fileList.size, 1)
            setTvStatus()
        }
        binding.idTvDelete.setOnClickListener {
            showDeletePermanentlyDialog {
                AdmobMaxHelper.admobMaxShowInterstitialAd(this, false) {
                    cleanFile()
                }
            }
        }
    }

    private fun cleanFile() {
        val list = fileList.toList().filter { it.isSelect }
        if (list.isNotEmpty() && list.all { NewFileUtils.delete(it.path) }) {
            fileList.removeAll(list)
            SimarPhotoUtils.similarImageList.removeAll(list)
            //    mAdapter.notifyDataSetChanged()
            binding.idRlList.adapter?.notifyDataSetChanged()
            setTvStatus()
            Toast.makeText(this, "Delete Successful", Toast.LENGTH_SHORT).show()
            val array = list.map { it.path }.toTypedArray()
            MediaStoreUtils.updateMediaStore(this, array)
        } else {
            Toast.makeText(this, "Delete failed.", Toast.LENGTH_SHORT).show()
        }
    }

    private var fileList = mutableListOf<ImageInfoBean>()




    private fun initAdapter() {
        binding.idRlList.run {
            layoutManager = GridLayoutManager(this@SimilarPicAt, 3)
            adapter = object : RecyclerView.Adapter<mViewHolder>() {
                override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): mViewHolder {
                    val view = LayoutInflater.from(context)
                        .inflate(R.layout.item_layout_repeater_photo, parent, false)
                    return mViewHolder(view)
                }

                @SuppressLint("SetTextI18n")
                override fun onBindViewHolder(holder: mViewHolder, position: Int) {
                    val item = fileList[position]
                    Glide.with(BaseApplication.context).load(item.path).into(holder.ivImage)
                    holder.ivSelect.isVisible = true
                    holder.itemView.setOnClickListener {

                        item.isSelect = !item.isSelect
                        notifyItemChanged(position, 1)

                        if (fileList.all { it.isSelect }) {
                            isSelectAll = true
                            binding.idTvAll.text = "Cancel"
                            binding.idImgSelect.setImageResource(R.mipmap.xuanzhong)
                        } else {
                            isSelectAll = false
                            binding.idTvAll.text = "All"
                            binding.idImgSelect.setImageResource(R.mipmap.weixuan)
                        }
                        setTvStatus()
                    }
                }

                override fun onBindViewHolder(
                    holder: mViewHolder,
                    position: Int,
                    payloads: MutableList<Any>
                ) {
                    super.onBindViewHolder(holder, position, payloads)
                    val item = fileList[position]
                    holder.ivSelect.setImageResource(
                        if (item.isSelect) {
                            R.mipmap.xuanzhong
                        } else {
                            R.mipmap.weixuan
                        }
                    )
                }

                override fun getItemCount() = fileList.size
            }
        }

    }

    private fun setTvStatus() {
        val it = fileList.filter { it.isSelect }
        binding.idTvDelete.isEnabled = it.isNotEmpty()
    }

    class mViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val ivImage: ImageView
        val ivSelect: ImageView

        init {
            ivImage = view.findViewById(R.id.iv_image)
            ivSelect = view.findViewById(R.id.id_img_sel)
        }
    }
}