package com.easy.clean.ui.photocompression

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.easy.clean.R
import com.easy.clean.base.BaseActivity
import com.easy.clean.base.LottieEnum
import com.easy.clean.bean.FeatureBean.Companion.PHOTO_COMPRESSION
import com.easy.clean.bean.FileBean
import com.easy.clean.business.ads.AdsMgr
import com.easy.clean.databinding.ActivityPhotoCompressionDetailBinding
import com.easy.clean.databinding.ItemPhotoDetailBinding
import com.easy.clean.ui.cleanresult.CleanResultActivity
import com.easy.clean.ui.dialog.ConfirmDialog
import com.easy.clean.ui.photocompression.CompressionUtils.compressSave
import com.easy.clean.utils.Utils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions

class PhotoCompressionDetailActivity :
    BaseActivity<ActivityPhotoCompressionDetailBinding>(ActivityPhotoCompressionDetailBinding::inflate) {

    companion object {
        var list = mutableListOf<FileBean>()
    }

    private lateinit var currentFile: FileBean
    private var mode = 1
    private var compressTotal: Long = 0
    private var selectedPosition = 0

    private val adapter by lazy {
        class ViewHolder(val binding: ItemPhotoDetailBinding) : RecyclerView.ViewHolder(binding.root)

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val binding = ItemPhotoDetailBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                return ViewHolder(binding)
            }

            override fun getItemCount(): Int = list.size

            @SuppressLint("SetTextI18n")
            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val context = holder.itemView.context
                val item = list[position]
                val width = resources.displayMetrics.widthPixels
                val viewWidth = width / 3
                holder.itemView.layoutParams.width = viewWidth

                val bgWidth = context.resources.getDimensionPixelSize(
                    if (position == selectedPosition) R.dimen.dp_80 else R.dimen.dp_60
                )

                holder.binding.llPhotoBg.layoutParams.width = bgWidth
                holder.binding.llPhotoBg.layoutParams.height = bgWidth
                holder.binding.llPhotoBg.setBackgroundResource(if (position == selectedPosition) R.drawable.photo_background else Color.TRANSPARENT)

                val round = context.resources.getDimensionPixelSize(R.dimen.dp_8)
                val options = RequestOptions().transform(CenterCrop(), RoundedCorners(round))
                Glide.with(holder.itemView.context)
                    .load(item.path)
                    .apply(options)
                    .into(holder.binding.ivPhoto)
                holder.binding.llPhotoBg.setOnClickListener {
                    if (selectedPosition == position) return@setOnClickListener
                    notifyItemChanged(selectedPosition)
                    selectedPosition = holder.getAdapterPosition()
                    notifyItemChanged(selectedPosition)

                    binding.tvCurrentCount.text = "${position + 1}"
                    currentFile = item
                    showPhoto()
                    compress()
                }
            }
        }
    }


    private fun showPhoto() {
        Glide.with(this).load(currentFile.path).into(binding.ivOriginalImage)
        binding.tvOriginalSize.text = Utils.getSizeFormat(currentFile.length)
    }

    private fun compress() {
        CompressionUtils.compressPhoto(currentFile.path, mode) { size, bitmap ->
            runOnUiThread {
                binding.tvCompressSize.text = Utils.getSizeFormat(size)
                if (bitmap != null) binding.ivCompressImage.setImageBitmap(bitmap)
            }
        }
    }

    override fun useDefaultImmersive() {
        setStatusBarColor()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            binding.clTop.setPadding(0, systemBars.top, 0, 0)
            insets
        }

    }

    override fun initView() {
        super.initView()
        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_native_custom)
        binding.llTitle.tvTitle.text=getString(R.string.photo_compression)
        binding.rvPhoto.adapter = adapter
        binding.rvPhoto.layoutManager = GridLayoutManager(this, 1, GridLayoutManager.HORIZONTAL, false)
        binding.tvTotalCount.text = "${list.size}"
        binding.tvCompressAll.text = getString(if (list.size > 1) R.string.compress_all else R.string.compress)
        binding.viewTriple.selection.observe(this) {
            mode = it
            showPhoto()
            compress()
        }
        currentFile = list[0]
    }

    override fun initListener() {
        super.initListener()
        binding.llTitle.ivBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.tvCompressAll.setOnClickListener {
            val dialog = ConfirmDialog(this)
            dialog.action = {
                compressSave()
                showAdAnimation(LottieEnum.PHOTO_COMPRESSION_LOTTIE) {
                    CleanResultActivity.functionKey = PHOTO_COMPRESSION
                    CleanResultActivity.titleName = getString(R.string.photo_compression)
                    CleanResultActivity.total = list.sumOf { it.length } - compressTotal
                    goToAc(CleanResultActivity::class.java)
                }
            }
            dialog.showDialog("")
        }
    }


    private fun compressSave() {
        list.forEach {
            compressSave(this, it.path, mode) { result, size ->
                if (result) {
                    compressTotal += size
                }
            }
        }
    }
}