package com.zxhy.fastfilemanagerpro.kokolistfile

import android.annotation.SuppressLint
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.ActivityKoListFilekoBinding
import com.zxhy.fastfilemanagerpro.kokodata.KoFileDatako
import com.zxhy.fastfilemanagerpro.kokodata.KoFileDatako.Companion.toFile
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 KoListFilekoActivity : AppCompatActivity() {

    private val viewModel: KoListFilekoViewModel by viewModels()
    private lateinit var binding: ActivityKoListFilekoBinding
    private lateinit var activityLauncher: ActivityLauncher
    private lateinit var adapter: KoListFilekoAdapter
    private var tittle = ""
    private lateinit var context: Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        context = this
        activityLauncher = ActivityLauncher(this)
        binding = ActivityKoListFilekoBinding.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
        }
        tittle = intent.extras?.getString("Tittle") ?: ""
        binding.tvTittle.text = tittle
        adapter = KoListFilekoAdapter {
            binding.ivAllSelector.isSelected = it
            enableDelete()
        }
        binding.rv.adapter = adapter
        binding.ivAllSelector.setOnClickListener {
            it.isSelected = !it.isSelected
            adapter.toggleSelect(it.isSelected)
            enableDelete()
        }
        binding.ivBack.setOnClickListener {
            finish()
        }

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

    }

    //region 通用ui操作
    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
            binding.tvSet.setOnClickListener {
                requestStoreFollow(activityLauncher, disAgreeAction = {
                    showPermissionSet(true)
                }, agreeAction = {
                    showPermissionSet(false)
                    loadListFile()
                })
            }
        } else {
            binding.clContent.visibility = View.VISIBLE
            binding.clPermissionSet.visibility = View.GONE
        }

    }

    private fun loadListFile() {
        when (tittle) {
            EMPTY_FILE -> viewModel.loadEmptyFile(context, ::onDoList, ::onFinishList)
            LARGE_FILE -> viewModel.loadLargeFile(context, ::onDoList, ::onFinishList)
            AUDIO_FILE -> viewModel.loadAudioFile(context, ::onDoList, ::onFinishList)
            LOG_FILE -> viewModel.loadLogFile(context, ::onDoList, ::onFinishList)
            ZIP_FILE -> viewModel.loadZipFile(context, ::onDoList, ::onFinishList)
            APK_FILE -> viewModel.loadApkFile(context, ::onDoList, ::onFinishList)
            DOCUMENTS_FILE -> viewModel.loadDocumentsFile(context, ::onDoList, ::onFinishList)
        }
    }

    fun enableDelete() {
        val enable = adapter.getSelectData().isNotEmpty()

        binding.tvDelete.isEnabled = enable

        if (enable) {
            binding.tvDelete.background =
                ContextCompat.getDrawable(context, R.drawable.bg_ffff6767_corners)
            binding.tvDelete.setTextColor(ContextCompat.getColor(context, R.color.white))
            binding.tvDelete.setOnClickListener {
                deleteFiles()
            }
        } else {
            binding.tvDelete.background =
                ContextCompat.getDrawable(context, R.drawable.bg_fff4f4f4_corners)
            binding.tvDelete.setTextColor(ContextCompat.getColor(context, R.color.color_999999))
            binding.tvDelete.setOnClickListener {}
        }
    }


    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 onDoList(list: List<KoFileDatako>) = lifecycleScope.launch(Dispatchers.Main) {
        adapter.setData(list)
    }

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


    private fun deleteFiles() {
        val selectData = adapter.getSelectData()
        val files = selectData.map { it.toFile() }
        viewModel.deleteFiles(files) {
            lifecycleScope.launch(Dispatchers.Main) {
                showOperationResult()
                adapter.removeData(selectData)
                showEmptyList()
                enableDelete()
            }
        }
    }
    //endregion


    companion object {
        const val EMPTY_FILE = "Empty file"
        const val LARGE_FILE = "Large file"
        const val AUDIO_FILE = "Audio file"
        const val LOG_FILE = "Log file"
        const val ZIP_FILE = "Zip"
        const val APK_FILE = "APK"
        const val DOCUMENTS_FILE = "documents file"
    }
}