package com.zxhy.fastfilemanagerpro.kokodup

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.zxhy.fastfilemanagerpro.R
import com.zxhy.fastfilemanagerpro.databinding.ActivityKoDupFilekoBinding
import com.zxhy.fastfilemanagerpro.kokodata.KoFileDatako
import com.zxhy.fastfilemanagerpro.kokodata.KoFileDatako.Companion.toFile
import com.zxhy.fastfilemanagerpro.kokodialog.LoadingDialog.showLoadingDialog
import com.zxhy.fastfilemanagerpro.kokotools.ActivityLauncher
import com.zxhy.fastfilemanagerpro.kokotools.permission.PermissionCheck.storePermissionCheck
import com.zxhy.fastfilemanagerpro.kokotools.permission.StorePermissionEx.requestStoreFollow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class KoDupFilekoActivity : AppCompatActivity() {
    private lateinit var binding: ActivityKoDupFilekoBinding
    private val viewModel: KoDupFilekoViewModel by viewModels()
    private lateinit var context: Context
    private lateinit var adapter: KoDupFilekoAdapter
    private lateinit var activityLauncher: ActivityLauncher
    private var tittle: String = ""
    private var dialog: Dialog? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        activityLauncher = ActivityLauncher(this)
        context = this
        binding = ActivityKoDupFilekoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        adapter = KoDupFilekoAdapter {
            binding.ivAllSelector.isSelected = it
            enableDelete()
        }
        binding.llAll.setOnClickListener {
            it.isSelected = !it.isSelected
            adapter.toggleSelect(it.isSelected)
            enableDelete()
        }
        binding.rv.adapter = adapter
        tittle = intent.extras?.getString("Tittle") ?: ""
        binding.tvTittle.text = tittle


        if (storePermissionCheck()) {
            showPermissionSet(false)
            loadListFile()
        } else {
            showPermissionSet(true)
        }

    }

    private fun loadListFile() {
        dialog = showLoadingDialog()
        when (tittle) {
            DUP_IMAGE -> viewModel.loadDupImage(context, ::onFinishList)
            DUP_FILE -> viewModel.loadDupFile(context, ::onFinishList)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun onFinishList(list: List<KoDupFileDatako>) =
        lifecycleScope.launch(Dispatchers.Main) {
            adapter.setData(list)
            showEmptyList()
            enableDelete()
            binding.tvItems.text = "total:${adapter.itemCount} items"
            dialog?.dismiss()
        }


    //region 公共ui逻辑
    private fun showEmptyList() {
        if (adapter.itemCount == 0) {
            binding.clEmpty.visibility = View.VISIBLE
            binding.clShowContent.visibility = View.GONE
            binding.llAll.visibility = View.GONE
        } else {
            binding.clEmpty.visibility = View.GONE
            binding.clShowContent.visibility = View.VISIBLE
            binding.llAll.visibility = View.VISIBLE
        }
    }

    private fun enableDelete() {
        val selectSubData = adapter.getSelectSubData()
        if (selectSubData.isEmpty()) {
            binding.tvDelete.isEnabled = false
            binding.tvDelete.background =
                ContextCompat.getDrawable(context, R.drawable.bg_fff4f4f4_corners)
            binding.tvDelete.setTextColor(ContextCompat.getColor(context, R.color.color_999999))
        } else {
            binding.tvDelete.isEnabled = true
            binding.tvDelete.background =
                ContextCompat.getDrawable(context, R.drawable.bg_ffff6767_corners)
            binding.tvDelete.setTextColor(ContextCompat.getColor(context, R.color.white))
            binding.tvDelete.setOnClickListener {
                deleteFiles(selectSubData)
            }
        }
    }

    fun showOperationResult() = lifecycleScope.launch(Dispatchers.Main) {
        binding.llResult.visibility = View.VISIBLE
        delay(500)
        binding.llResult.visibility = View.GONE
    }

    fun showPermissionSet(show: Boolean) {
        if (show) {
            binding.clContent.visibility = View.GONE
            binding.clPermissionSet.visibility = View.VISIBLE
            window.statusBarColor = ContextCompat.getColor(context, R.color.color_b3000000)
            binding.tvSet.setOnClickListener {
                requestStoreFollow(activityLauncher, disAgreeAction = {
                    showPermissionSet(true)
                }, agreeAction = {
                    showPermissionSet(false)
                    loadListFile()
                })
            }
        } else {
            binding.clContent.visibility = View.VISIBLE
            binding.clPermissionSet.visibility = View.GONE
            window.statusBarColor = ContextCompat.getColor(context, R.color.white)
        }

    }

    private fun deleteFiles(selectSubData: List<KoFileDatako>) {
        val files = selectSubData.map { it.toFile() }
        viewModel.deleteFiles(files) {
            lifecycleScope.launch(Dispatchers.Main) {
                showOperationResult()
                adapter.removeSubData(selectSubData)
                showEmptyList()
                enableDelete()
            }
        }
    }
    //endregion

    companion object {
        const val DUP_IMAGE = "Scan for duplicate pictures"
        const val DUP_FILE = "Scan for duplicate files"
    }

}