package com.zxhy.fastfilemanagerpro.gridfile

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.ActivityKoGridFilekoBinding
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 KoGridFilekoActivity : AppCompatActivity() {
    private lateinit var binding: ActivityKoGridFilekoBinding
    private val viewModel: KoGridFilekoViewModel by viewModels()
    private lateinit var activityLauncher: ActivityLauncher
    private var tittle = ""
    private lateinit var adapter: KoFileGridkoAdapter
    private lateinit var context: Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        context = this
        activityLauncher = ActivityLauncher(this)
        binding = ActivityKoGridFilekoBinding.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 = KoFileGridkoAdapter {
            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
    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
        }

    }

    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 deleteFiles() {
        val selectData = adapter.getSelectData()
        val files = selectData.map { it.toFile() }
        viewModel.deleteFiles(files) {
            lifecycleScope.launch(Dispatchers.Main) {
                showOperationResult()
                adapter.removeData(selectData)
                showEmptyList()
                enableDelete()
            }
        }
    }

    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.tvItems.text = "total:${adapter.itemCount} items"
    }

    //endregion

    private fun loadListFile() {
        when (tittle) {
            IMAGE_FILE -> viewModel.loadImageFile(context, ::onDoList, ::onFinishList)
            VIDEO_FILE -> viewModel.loadVideoFile(context, ::onDoList, ::onFinishList)
        }
    }

    companion object {
        const val IMAGE_FILE = "Image file"
        const val VIDEO_FILE = "Video file"
    }
}