package com.test.basd.fastcleanerjunk.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
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.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.test.basd.fastcleanerjunk.R
import com.test.basd.fastcleanerjunk.bean.ImageDataBean
import com.test.basd.fastcleanerjunk.databinding.ActivityLayoutRepeaterdPhotoBinding
import com.test.basd.fastcleanerjunk.helps.BaseActivity
import com.test.basd.fastcleanerjunk.helps.BaseApplication
import com.test.basd.fastcleanerjunk.helps.FileHelps
import com.test.basd.fastcleanerjunk.helps.PermissionHelp.checkStorePermission
import com.test.basd.fastcleanerjunk.helps.PermissionHelp.requestStorePermission
import com.test.basd.fastcleanerjunk.helps.ads.AdmobUtils
import com.test.basd.fastcleanerjunk.view.DialogViews

class PreparedPhotoActivity : BaseActivity<ActivityLayoutRepeaterdPhotoBinding>() {

    private var isSelectAll = false

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

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        binding.idTvDelete.isEnabled = false

        if (checkStorePermission()) {
            initData()
        } else {
            DialogViews.showGerPermission(this, {
                requestStorePermission(launcher, result = { flag ->
                    if (flag) {
                        initData()
                    } else {
                        finishToMain()
                    }
                }, resolveNoAction = { finishToMain() })
                PermissionTripActivity.launch(this)
            }, {
                finishToMain()
            })
        }
    }

    override fun initListener() {
        binding.idBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                AdmobUtils.showInterstitialAd(this@PreparedPhotoActivity) {
                    finishToMain()
                }

            }
        })

        binding.idImgSelect.setOnClickListener {
            if (isSelectAll) {
                isSelectAll = false
                binding.idTvAll.text = "All"
                binding.idImgSelect.setImageResource(R.mipmap.xuan_3)
            } else {
                isSelectAll = true
                binding.idTvAll.text = "Cancel"
                binding.idImgSelect.setImageResource(R.mipmap.danxuanxe)
            }
            fileList.forEach { it.isSelect = isSelectAll }
            mAdapter.notifyItemRangeChanged(0, fileList.size, 1)
            setTvStatus()
        }
        binding.idTvDelete.setOnClickListener {
            AdmobUtils.showInterstitialAd(this) {
                val list = fileList.toList().filter { it.isSelect }
                if (list.isNotEmpty() && list.all { FileUtils.delete(it.path) }) {
                    fileList.removeAll(list)
                    FileHelps.similarImageList.removeAll(list)
                    mAdapter.notifyDataSetChanged()
                    setTvStatus()
                    ToastUtils.showShort("Delete Successful")
                } else {
                    ToastUtils.showShort("Delete failed.")
                }
            }

        }
    }

    private var fileList = mutableListOf<ImageDataBean>()

    private fun initData() {

        FileHelps.getImageFiles {
            AdmobUtils.showInterstitialAd(this)
            binding.idLlScaning.isVisible = false
            binding.idLlResult.isVisible = true
            fileList = FileHelps.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
            binding.idRlList.layoutManager = GridLayoutManager(this, 3)
            binding.idRlList.adapter = mAdapter
        }
    }

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

    private val mAdapter by lazy {
        class ViewHolder(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)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@PreparedPhotoActivity).inflate(
                    R.layout.item_layout_repeater_photo, parent, false
                )
                return ViewHolder(view)
            }

            override fun getItemCount() = fileList.size

            @SuppressLint("SetTextI18n")
            override fun onBindViewHolder(holder: ViewHolder, 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.danxuanxe)
                    } else {
                        isSelectAll = false
                        binding.idTvAll.text = "All"
                        binding.idImgSelect.setImageResource(R.mipmap.xuan_3)
                    }
                    setTvStatus()
                }
            }

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