package warpic

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.activity.SystemBarStyle
import androidx.activity.addCallback
import androidx.activity.enableEdgeToEdge
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 com.easy.clean.R
import tooic.fatalityic.jittersic.Reinstateic
import tooic.fatalityic.corroborateic.poisedic.drowningic.rainic.Usefulnessic
import tooic.fatalityic.corroborateic.poisedic.drowningic.rainic.Irritantic
import tooic.fatalityic.corroborateic.poisedic.drowningic.rainic.Schemeic
import com.easy.clean.databinding.JinxedicBinding
import warpic.Shamrockic.Companion.SCAN_AUDIOS
import warpic.Shamrockic.Companion.SCAN_DOCUMENTS
import warpic.Shamrockic.Companion.SCAN_PHOTOS
import warpic.Shamrockic.Companion.SCAN_VIDEOS
import warpic.Gooic.showRecoveringDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

class Discretionaryic : Reinstateic<JinxedicBinding>(JinxedicBinding::inflate) {

    private var scanType = 0

    private lateinit var adapter: Exonerateic
    private lateinit var filterAdapter: Goingic

    private val dateFilterList = arrayListOf(
        Schemeic("All", "Size", true),
        Schemeic("With 1 month", "Date"),
        Schemeic("With 6 months", "Date"),
        Schemeic("With 24 months", "Date"),
    )
    private var sizeFilterList = arrayListOf(
        Schemeic("All", "Size", true),
        Schemeic("0 - 1 M", "Size"),
        Schemeic("1 - 5 M", "Size"),
        Schemeic("> 5 M", "Size"),
    )

    private val layoutFilterList = arrayListOf(
        Schemeic("2 columns", "Layout", true),
        Schemeic("3 columns", "Layout"),
        Schemeic("4 columns", "Layout"),
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initListener()
    }

    override fun useDefaultImmersive() {
        enableEdgeToEdge(SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT))
        ViewCompat.setOnApplyWindowInsetsListener(binding.overseeric) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {


        scanType = intent.extras?.getInt("ScanType") ?: 0

        when (scanType) {
            SCAN_PHOTOS -> {
                setThumbnails()
            }

            SCAN_DOCUMENTS -> {
                binding.rotisserieic.visibility = View.GONE
                binding.supervisionic.visibility = View.GONE
            }

            SCAN_VIDEOS -> {
                binding.rotisserieic.visibility = View.GONE
            }

            SCAN_AUDIOS -> {
                binding.rotisserieic.visibility = View.GONE
                binding.supervisionic.visibility = View.GONE
            }

        }
        adapter = Exonerateic(
            scanType,
            select = { all, size ->
                binding.vestibuleic.isSelected = all
                binding.fungiic.text = "Recover($size)"
                binding.fungiic.isEnabled = size > 0
            })
        binding.callingic.adapter = adapter

        filterAdapter = Goingic { bean ->
            filterDismiss(bean)
        }
        binding.deodorizeic.adapter = filterAdapter

        initData()
    }

    @SuppressLint("SetTextI18n")
    private fun setThumbnails() = lifecycleScope.launch(Dispatchers.IO) {

        var size = 0
        folderBean?.recoveryList?.forEach { bean ->
            runCatching {
                val bitmap: Bitmap? = BitmapFactory.decodeFile(bean.path)
                bitmap?.let {
                    if (it.height < 256 || it.width < 256) {
                        size++
                        bean.isThumbnails = true
                    }
                }
            }
        }
        launch(Dispatchers.Main) {
            binding.stingyic.text = "Hide thumbnails (${size})"
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun initListener() {
        binding.blowtorchic.setOnClickListener {
            filterDismiss()
        }
        binding.troutic.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.firmic.setOnCheckedChangeListener { buttonView, isChecked ->
            adapter.toggleThumbnails(isChecked)
        }
        binding.pedestrianic.setOnClickListener {
            binding.vestibuleic.isSelected = !binding.vestibuleic.isSelected
            adapter.toggleAllSelect(binding.vestibuleic.isSelected)
        }
        binding.heartsic.setOnClickListener {
            showFilter(it.id)
        }
        binding.lyricsic.setOnClickListener {
            showFilter(it.id)
        }
        binding.supervisionic.setOnClickListener {
            showFilter(it.id)
        }
        binding.fungiic.setOnClickListener {
            var dirType = ""
            when (scanType) {
                SCAN_PHOTOS -> dirType = "Photo"
                SCAN_DOCUMENTS -> dirType = "Document"
                SCAN_VIDEOS -> dirType = "Video"
                SCAN_AUDIOS -> dirType = "Audio"
            }
            val appName = getString(R.string.overrodeic).replace("/", " ")
            val appDir = File(Environment.getExternalStorageDirectory(), appName)
            val dir = File(appDir, dirType)
            if (!dir.exists()) {
                dir.mkdirs()
            }
            beginRecover(dir)
        }
    }

    private fun beginRecover(dir: File) {
        val list = adapter.getSelectData().map { it.path }
        showRecoveringDialog(lifecycleScope, list, dir, copyProgressAction = {

        }, finish = {
            startActivity(Intent(this, Nauticalic::class.java).apply {
                putExtra("Number", list.size)
                putExtra("ScanType", scanType)
            })
        })
    }

    private fun showFilter(filter: Int) {

        if (!binding.blowtorchic.isVisible) {
            binding.blowtorchic.isVisible = true
            binding.overseeric.background = ContextCompat.getDrawable(this, R.drawable.defectiveic)
        }

        if (filter == R.id.heartsic) {
            binding.sassic.setImageResource(R.drawable.actualityic)
            filterAdapter.setData(dateFilterList)
        } else {
            binding.sassic.setImageResource(R.drawable.enticementic)
        }
        if (filter == R.id.lyricsic) {
            binding.trainic.setImageResource(R.drawable.actualityic)
            filterAdapter.setData(sizeFilterList)
        } else {
            binding.trainic.setImageResource(R.drawable.enticementic)
        }
        if (filter == R.id.supervisionic) {
            binding.riggingic.setImageResource(R.drawable.actualityic)
            filterAdapter.setData(layoutFilterList)
        } else {
            binding.riggingic.setImageResource(R.drawable.enticementic)
        }
    }

    private fun filterDismiss(recoveryFilterBean: Schemeic? = null) {
        binding.blowtorchic.isVisible = false
        binding.overseeric.background = ContextCompat.getDrawable(this, R.drawable.defectiveic)
        binding.sassic.setImageResource(R.drawable.enticementic)
        binding.trainic.setImageResource(R.drawable.enticementic)
        binding.riggingic.setImageResource(R.drawable.enticementic)

        recoveryFilterBean?.let { bean ->
            if (bean.type == "Date") {
                dateFilterList.find { it.isSelect }?.isSelect = false
                dateFilterList.find { it == bean }?.isSelect = true
                initData()
                return
            }
            if (bean.type == "Size") {
                sizeFilterList.find { it.isSelect }?.isSelect = false
                sizeFilterList.find { it == bean }?.isSelect = true
                initData()
                return
            }
            if (bean.type == "Layout") {
                layoutFilterList.find { it.isSelect }?.isSelect = false
                layoutFilterList.find { it == bean }?.isSelect = true

                val index = layoutFilterList.indexOf(bean)
                val columns = when (index) {
                    0 -> 2
                    1 -> 3
                    2 -> 4
                    else -> 2
                }
                adapter.changeColumns(columns)
            }
        }

    }

    private fun Long.toFormatTime(): String {
        return SimpleDateFormat("MMM dd,yyyy", Locale.ENGLISH).format(this)
    }

    fun initData() {

        val hash = HashMap<String, ArrayList<Irritantic>>()

        folderBean?.let {
            it.recoveryList.forEach { recoveryBean ->
                if (dateFilter(recoveryBean) && sizeFilter(recoveryBean)) {
                    val file = File(recoveryBean.path)
                    val time = file.lastModified().toFormatTime()
                    if (hash[time].isNullOrEmpty()) {
                        hash[time] = arrayListOf()
                    }
                    hash[time]?.add(recoveryBean)
                }

            }
        }
        val list = arrayListOf<Usefulnessic>()
        hash.forEach { (key, value) ->
            list.add(Usefulnessic(time = key, recoveryList = value))
        }
        adapter.setData(list)
    }

    private fun dateFilter(recoveryBean: Irritantic): Boolean {
        val index = dateFilterList.indexOfFirst { it.isSelect }
        return when (index) {
            1 -> isWithinOneMonth(File(recoveryBean.path).lastModified())
            2 -> isWithinSixMonths(File(recoveryBean.path).lastModified())
            3 -> isWithinTwentyFourMonths(File(recoveryBean.path).lastModified())
            else -> true
        }
    }

    private fun sizeFilter(recoveryBean: Irritantic): Boolean {
        val oneMegabyte = 1024 * 1024L
        val index = sizeFilterList.indexOfFirst { it.isSelect }

        return when (index) {
            1 -> File(recoveryBean.path).length() in 0L..oneMegabyte
            2 -> File(recoveryBean.path).length() in oneMegabyte..oneMegabyte * 5
            3 -> File(recoveryBean.path).length() > oneMegabyte * 5
            else -> true
        }
    }

    companion object {
        var folderBean: Usefulnessic? = Usefulnessic()
    }


    fun isWithinOneMonth(pastTimestamp: Long): Boolean {
        val calendar = Calendar.getInstance()
        val currentTime = System.currentTimeMillis()

        // 将当前时间减去一个月
        calendar.timeInMillis = currentTime
        calendar.add(Calendar.MONTH, -1)
        val oneMonthAgo = calendar.timeInMillis

        // 检查过去的时间戳是否在当前时间与一个月前之间
        return pastTimestamp in oneMonthAgo..currentTime
    }

    fun isWithinSixMonths(pastTimestamp: Long): Boolean {
        val calendar = Calendar.getInstance() // 获取当前时间的Calendar实例
        val currentTime = System.currentTimeMillis() // 获取当前时间的时间戳

        // 设置calendar到当前时间
        calendar.timeInMillis = currentTime
        // 减去6个月
        calendar.add(Calendar.MONTH, -6)

        val sixMonthsAgo = calendar.timeInMillis // 计算6个月前的日期

        // 检查过去的时间戳是否在6个月的范围内
        return pastTimestamp in sixMonthsAgo..currentTime
    }

    fun isWithinTwentyFourMonths(timestamp: Long): Boolean {
        val calendar = Calendar.getInstance() // 获取当前时间的Calendar实例
        val currentTime = System.currentTimeMillis() // 获取当前时间的时间戳

        // 设置calendar到当前时间
        calendar.timeInMillis = currentTime
        // 减去24个月
        calendar.add(Calendar.MONTH, -24)

        val twentyFourMonthsAgo = calendar.timeInMillis // 计算24个月前的日期

        // 检查时间戳是否在24个月的范围内
        return timestamp in twentyFourMonthsAgo..currentTime
    }

}

