package com.simplecleaner.app.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.simplecleaner.app.R
import com.simplecleaner.app.base.BaseActivity
import com.simplecleaner.app.base.LottieEnum
import com.simplecleaner.app.bean.FeatureBean.Companion.PHOTO_COMPRESSION
import com.simplecleaner.app.bean.FileBean
import com.simplecleaner.app.business.ads.AdsMgr
import com.simplecleaner.app.databinding.ActivityPhotoCompressionDetailBinding
import com.simplecleaner.app.databinding.ItemPhotoDetailBinding
import com.simplecleaner.app.ui.cleanresult.CleanResultActivity
import com.simplecleaner.app.ui.dialog.ConfirmDialog
import com.simplecleaner.app.ui.photocompression.CompressionUtils.compressSave
import com.simplecleaner.app.utils.LogEx
import com.simplecleaner.app.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
                    compress()
                }
            }
        }
    }


    private fun showPhoto() {
        LogEx.logDebug(TAG, "showPhoto ${currentFile.path}")
        Glide.with(this).load(currentFile.path).into(binding.ivOriginalImage)
        binding.tvOriginalSize.text = Utils.getSizeFormat(currentFile.length)
    }

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

    override fun useDefaultImmersive() {
        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.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
            compress()
        }
        currentFile = list[0]
    }

    override fun initListener() {
        super.initListener()
        binding.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
                }
            }
        }
    }
}