package com.simplecleaner.app.ui.largefile

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
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.base.cleanFileBeans
import com.simplecleaner.app.bean.FeatureBean.Companion.LARGE_FILE_CLEAN
import com.simplecleaner.app.bean.FileBean
import com.simplecleaner.app.business.ads.AdsMgr
import com.simplecleaner.app.business.ads.AdsShowCallBack
import com.simplecleaner.app.databinding.ActivityLargeFileCleanBinding
import com.simplecleaner.app.databinding.ItemLargeFileCleanBinding
import com.simplecleaner.app.databinding.ItemLargeFileCleanTabBinding
import com.simplecleaner.app.ui.cleanresult.CleanResultActivity
import com.simplecleaner.app.ui.dialog.ConfirmDialog
import com.simplecleaner.app.utils.MediaUtils
import com.simplecleaner.app.utils.MineTypeUtils
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
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.Calendar
import androidx.activity.viewModels
import com.simplecleaner.app.ui.largefile.LargeFileCleanViewModel
import com.simplecleaner.app.ui.largefile.LargeFileCleanAdapter


class LargeFileCleanActivity : BaseActivity<ActivityLargeFileCleanBinding>(ActivityLargeFileCleanBinding::inflate) {

    private val viewModel: LargeFileCleanViewModel by viewModels()
    private val LARGE_FILE_SIZE: Long = 1024 * 1024 * 10
    private val typeList by lazy {
        listOf(
            FileBean(getString(R.string.all_types), isSelected = true),
            FileBean(getString(R.string.image)),
            FileBean(getString(R.string.video)),
            FileBean(getString(R.string.audio)),
            FileBean(getString(R.string.document)),
            FileBean(getString(R.string.apk)),
            FileBean(getString(R.string.other_types)),
        )
    }
    private val sizeList by lazy {
        listOf(
            FileBean(getString(R.string.mb_10), isSelected = true),
            FileBean(getString(R.string.mb_20)),
            FileBean(getString(R.string.mb_50)),
            FileBean(getString(R.string.mb_100)),
            FileBean(getString(R.string.mb_500)),
        )
    }
    private val timeList by lazy {
        listOf(
            FileBean(getString(R.string.all_time), isSelected = true),
            FileBean(getString(R.string.week_1)),
            FileBean(getString(R.string.month_1)),
            FileBean(getString(R.string.month_3)),
            FileBean(getString(R.string.month_6)),
            FileBean(getString(R.string.year_1)),
        )
    }

    private val adapter: LargeFileCleanAdapter by lazy {
        LargeFileCleanAdapter(emptyList()) { position ->
            viewModel.toggleSelect(position)
            adapter.notifyItemChanged(position)
            updateView()
        }
    }

    private var tabType = 0
    private val tabList = mutableListOf<FileBean>()
    private val tabAdapter by lazy {
        class ViewHolder(val binding: ItemLargeFileCleanTabBinding) : RecyclerView.ViewHolder(binding.root)

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

            override fun getItemCount(): Int = tabList.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = tabList[position]
                holder.binding.tvName.text = item.name
                holder.binding.tvName.setTextColor(getColor(if (item.isSelected) R.color.colorPrimary else R.color.color_666666))
                holder.binding.viewLine.visibility = if (position == itemCount - 1) View.GONE else View.VISIBLE
                holder.binding.ivSelect.isSelected = item.isSelected
                holder.itemView.setOnClickListener {
                    tabList.forEach { it.isSelected = false }
                    item.isSelected = !item.isSelected
                    handleTab(item, position)
                }
            }
        }
    }

    private fun updateView() {
        val total = viewModel.getFilteredList().filter { it.isSelected }.sumOf { it.length }
        setTextSize(binding.tvDelete, getString(R.string.delete), total)
        binding.tvDelete.isEnabled = total > 0
        if (binding.tvDelete.isEnabled == true) {
            binding.tvDelete.setTextColor(ContextCompat.getColor(this, R.color.white))
        } else {
            binding.tvDelete.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
        }
    }

    private fun handleTab(item: FileBean, position: Int) {
        binding.clTab.visibility = View.GONE
        var textView: AppCompatTextView = binding.tvTime
        when (tabType) {
            1 -> {
                textView = binding.tvType
                viewModel.typePosition = position
            }

            2 -> {
                textView = binding.tvSize
                viewModel.sizePosition = position
            }

            3 -> {
                textView = binding.tvTime
                viewModel.timePosition = position
            }
        }
        textView.text = item.name
        binding.tvDelete.text = getString(R.string.delete)
        filterData()
        clearTab()
    }

    fun setTextSize(view: TextView, content: String, total: Long) {
        view.text = if (total > 0) "$content (${Utils.getSizeFormat(total)})" else content
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun filterData() {
        viewModel.filterData()
        adapter.setData(viewModel.getFilteredList())
        binding.rvLargeFile.visibility = if (viewModel.getFilteredList().isEmpty()) View.GONE else View.VISIBLE
        binding.ivEmpty.visibility = if (viewModel.getFilteredList().isEmpty()) View.VISIBLE else View.GONE
        binding.tvDelete.visibility = if (viewModel.getFilteredList().isEmpty()) View.GONE else View.VISIBLE
        updateView()
    }

    private fun clearTab() {
        binding.llTab.setBackgroundResource(R.color.color_f7fafa)
        binding.tvDelete.isEnabled = false
        binding.llType.setBackgroundResource(R.drawable.tab_large_file)
        binding.llSize.setBackgroundResource(R.drawable.tab_large_file)
        binding.llTime.setBackgroundResource(R.drawable.tab_large_file)
        binding.ivType.isSelected = false
        binding.ivSize.isSelected = false
        binding.ivTime.isSelected = false
        binding.tvType.setTextColor(getColor(R.color.color_181b1f))
        binding.tvSize.setTextColor(getColor(R.color.color_181b1f))
        binding.tvTime.setTextColor(getColor(R.color.color_181b1f))
        binding.ivTypeArrow.setImageResource(R.drawable.icon_jiantou_down_small)
        binding.ivSizeArrow.setImageResource(R.drawable.icon_jiantou_down_small)
        binding.ivTimeArrow.setImageResource(R.drawable.icon_jiantou_down_small)
        binding.llType.isSelected = false
        binding.llSize.isSelected = false
        binding.llTime.isSelected = false
    }


    private fun setTab(
        view: View,
        textView: AppCompatTextView,
        imageView: AppCompatImageView
    ) {
        if (view.isSelected) {
            hiddenTab()
            return
        }
        clearTab()
        view.isSelected = true
        view.setBackgroundResource(R.drawable.bg_btn_50)
        imageView.setImageResource(R.drawable.icon_jiantou_up_small)
        textView.setTextColor(getColor(R.color.white))
        binding.llTab.setBackgroundResource(R.color.white)
        when (view) {
            binding.llType -> {
                binding.ivType.isSelected = true
                binding.tvOtherThan.visibility = View.GONE
                showTab(1, typeList)
                viewModel.typePosition = 1
            }

            binding.llSize -> {
                binding.ivSize.isSelected = true
                binding.tvOtherThan.text = getString(R.string.larger_than)
                binding.tvOtherThan.visibility = View.VISIBLE
                showTab(2, sizeList)
                viewModel.sizePosition = 2
            }

            binding.llTime -> {
                binding.ivTime.isSelected = true
                binding.tvOtherThan.text = getString(R.string.other_types)
                binding.tvOtherThan.visibility = View.VISIBLE
                showTab(3, timeList)
                viewModel.timePosition = 3
            }
        }
        filterData()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun showTab(type: Int, list: List<FileBean>) {
        binding.clTab.visibility = View.VISIBLE
        tabType = type
        tabList.clear()
        tabList.addAll(list)
        tabAdapter.notifyDataSetChanged()
    }

    private fun hiddenTab() {
        binding.clTab.visibility = View.GONE
        binding.llType.isSelected = false
        binding.llSize.isSelected = false
        binding.llTime.isSelected = false
        clearTab()
    }

    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()
        binding.rvTab.adapter = tabAdapter
        binding.rvTab.layoutManager = LinearLayoutManager(this)
        binding.rvLargeFile.adapter = adapter
        binding.rvLargeFile.layoutManager = LinearLayoutManager(this)
        viewModel.largeFileSize = 1024 * 1024 * 10
        viewModel.loadFiles(this) {
            adapter.setData(viewModel.getFilteredList())
            updateView()
            binding.rvLargeFile.visibility = if (viewModel.getFilteredList().isEmpty()) View.GONE else View.VISIBLE
            binding.ivEmpty.visibility = if (viewModel.getFilteredList().isEmpty()) View.VISIBLE else View.GONE
            binding.tvDelete.visibility = if (viewModel.getFilteredList().isEmpty()) View.GONE else View.VISIBLE
        }
        showAdAnimation(LottieEnum.LARGE_FILE_LOTTIE) {
            AdsMgr.showNative(binding.flAd, R.layout.layout_admob_native_custom)
        }
    }

    override fun initListener() {
        super.initListener()
        binding.ivBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        binding.llType.setOnClickListener {
            setTab(it, binding.tvType, binding.ivTypeArrow)
        }
        binding.llSize.setOnClickListener {
            setTab(it, binding.tvSize, binding.ivSizeArrow)
        }
        binding.llTime.setOnClickListener {
            setTab(it, binding.tvTime, binding.ivTimeArrow)
        }
        binding.clTab.setOnClickListener {
            hiddenTab()
        }
        binding.tvDelete.setOnClickListener {
            if (viewModel.getFilteredList().isEmpty() || viewModel.getFilteredList().filter { it.isSelected }
                    .sumOf { it.length } <= 0) return@setOnClickListener
            val dialog = ConfirmDialog(this)
            dialog.action = {
                cleanFileBeans(viewModel.getFilteredList())
                AdsMgr.showInsert(this, showCallBack = object : AdsShowCallBack() {
                    override fun next() {
                        CleanResultActivity.functionKey = LARGE_FILE_CLEAN
                        CleanResultActivity.total = viewModel.getFilteredList().filter { it.isSelected }.sumOf { it.length }
                        CleanResultActivity.titleName = getString(R.string.large_file_clean)
                        goToAc(CleanResultActivity::class.java)
                    }
                })
            }
            dialog.showDialog("delete")
        }
    }

}