package com.easy.clean.ui.recovery

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 com.easy.clean.base.BaseActivity
import com.easy.clean.bean.recovery.FolderBean
import com.easy.clean.bean.recovery.RecoveryBean
import com.easy.clean.bean.recovery.RecoveryFilterBean
import com.easy.clean.databinding.ActivityFileRecoveryBinding
import com.easy.clean.ui.recovery.FileScanResultActivity.Companion.SCAN_AUDIOS
import com.easy.clean.ui.recovery.FileScanResultActivity.Companion.SCAN_DOCUMENTS
import com.easy.clean.ui.recovery.FileScanResultActivity.Companion.SCAN_PHOTOS
import com.easy.clean.ui.recovery.FileScanResultActivity.Companion.SCAN_VIDEOS
import com.easy.clean.ui.recovery.RecoveringDialog.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 FileRecoveryActivity : BaseActivity<ActivityFileRecoveryBinding>(ActivityFileRecoveryBinding::inflate) {

    private var scanType = 0

    private lateinit var adapter: FileTimeColumnsAdapter
    private lateinit var filterAdapter: RecoveryFilterAdapter

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

    private val layoutFilterList = arrayListOf(
        RecoveryFilterBean("2 columns", "Layout", true),
        RecoveryFilterBean("3 columns", "Layout"),
        RecoveryFilterBean("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.clTop) { 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.clThumbnails.visibility = View.GONE
                binding.llLayout.visibility = View.GONE
            }

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

            SCAN_AUDIOS -> {
                binding.clThumbnails.visibility = View.GONE
                binding.llLayout.visibility = View.GONE
            }

        }
        adapter = FileTimeColumnsAdapter(
            scanType,
            select = { all, size ->
                binding.ivSelectAll.isSelected = all
                binding.tvRecover.text = "Recover($size)"
                binding.tvRecover.isEnabled = size > 0
            })
        binding.rv.adapter = adapter

        filterAdapter = RecoveryFilterAdapter { bean ->
            filterDismiss(bean)
        }
        binding.rvFilter.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.tvThumbnails.text = "Hide thumbnails (${size})"
        }
    }

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

    override fun initListener() {
        binding.llFilter.setOnClickListener {
            filterDismiss()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.switchThumbnails.setOnCheckedChangeListener { buttonView, isChecked ->
            adapter.toggleThumbnails(isChecked)
        }
        binding.flSelectAll.setOnClickListener {
            binding.ivSelectAll.isSelected = !binding.ivSelectAll.isSelected
            adapter.toggleAllSelect(binding.ivSelectAll.isSelected)
        }
        binding.llDate.setOnClickListener {
            showFilter(it.id)
        }
        binding.llSize.setOnClickListener {
            showFilter(it.id)
        }
        binding.llLayout.setOnClickListener {
            showFilter(it.id)
        }
        binding.tvRecover.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.app_name).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, FileRecoveredActivity::class.java).apply {
                putExtra("Number", list.size)
                putExtra("ScanType", scanType)
            })
        })
    }

    private fun showFilter(filter: Int) {

        if (!binding.llFilter.isVisible) {
            binding.llFilter.isVisible = true
            binding.clTop.background = ContextCompat.getDrawable(this, R.drawable.bg_e7ecff_edf5ff_blr15)
        }

        if (filter == R.id.ll_date) {
            binding.ivDate.setImageResource(R.drawable.zhankai)
            filterAdapter.setData(dateFilterList)
        } else {
            binding.ivDate.setImageResource(R.drawable.shouqi)
        }
        if (filter == R.id.ll_size) {
            binding.ivSize.setImageResource(R.drawable.zhankai)
            filterAdapter.setData(sizeFilterList)
        } else {
            binding.ivSize.setImageResource(R.drawable.shouqi)
        }
        if (filter == R.id.ll_layout) {
            binding.ivLayout.setImageResource(R.drawable.zhankai)
            filterAdapter.setData(layoutFilterList)
        } else {
            binding.ivLayout.setImageResource(R.drawable.shouqi)
        }
    }

    private fun filterDismiss(recoveryFilterBean: RecoveryFilterBean? = null) {
        binding.llFilter.isVisible = false
        binding.clTop.background = ContextCompat.getDrawable(this, R.drawable.bg_e7ecff_edf5ff_blr15)
        binding.ivDate.setImageResource(R.drawable.shouqi)
        binding.ivSize.setImageResource(R.drawable.shouqi)
        binding.ivLayout.setImageResource(R.drawable.shouqi)

        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<RecoveryBean>>()

        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<FolderBean>()
        hash.forEach { (key, value) ->
            list.add(FolderBean(time = key, recoveryList = value))
        }
        adapter.setData(list)
    }

    private fun dateFilter(recoveryBean: RecoveryBean): 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: RecoveryBean): 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: FolderBean? = FolderBean()
    }


    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
    }

}

