package com.zxhy.simplefilesmanager.simplelist

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.zxhy.simplefilesmanager.R
import com.zxhy.simplefilesmanager.databinding.ActivitySimpleListBinding
import com.zxhy.simplefilesmanager.databinding.PopupwindowFileFilterBinding
import com.zxhy.simplefilesmanager.simpledata.JoFileJo
import com.zxhy.simplefilesmanager.simpledata.JoGridFileJo
import com.zxhy.simplefilesmanager.simpledata.JoListFileJo
import com.zxhy.simplefilesmanager.simpledata.JoListFileJo.Companion.isImage
import com.zxhy.simplefilesmanager.simpledata.JoListFileJo.Companion.isVideo
import com.zxhy.simplefilesmanager.simplegrid.SimpleGridAdapter
import com.zxhy.simplefilesmanager.simplejoke.JoActivityJoLauncher
import com.zxhy.simplefilesmanager.simplejoke.permission.JoPermissionJoCheckEx.jostorejoPermissionCheck
import com.zxhy.simplefilesmanager.simplejoke.permission.JoStoreJoPermissionEx.jorequestjoStoreFollow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SimpleListActivity : AppCompatActivity() {

    private lateinit var binding: ActivitySimpleListBinding
    private val viewModel: SimpleListViewModel by viewModels()
    private lateinit var fileAdapter: SimpleListAdapter
    private lateinit var imagerAdapter: SimpleGridAdapter
    private lateinit var videoAdapter: SimpleGridAdapter
    private var tittle: String = ""
    private var listData = arrayListOf<JoListFileJo>()
    private var canFilter = false

    private var showFileRv = true
    private var showImageRv = true
    private var showVideoRv = true

    private var imageEnable = true
    private var fileEnable = true
    private var videoEnable = true

    private var fileSelectCount = 0
    private var imageSelectCount = 0
    private var videoSelectCount = 0
    private lateinit var launcher: JoActivityJoLauncher

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        launcher = JoActivityJoLauncher(this)
        binding = ActivitySimpleListBinding.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


        initAdapter()
        if (!jostorejoPermissionCheck()) {
            showPermissionSet()
        } else {
            loadData()
        }
        binding.flBack.setOnClickListener {
            finish()
        }
    }

    private fun showPermissionSet() {
        binding.flPermissionSet.visibility = View.VISIBLE
        binding.tvSet.setOnClickListener {
            jorequestjoStoreFollow(launcher,
                disAgreeAction = {
                },
                agreeAction = {
                    binding.flPermissionSet.visibility = View.GONE
                    loadData()
                })
        }
    }

    private fun loadData() {
        binding.pb.visibility = View.VISIBLE
        when (tittle) {
            "AUDIO" -> {
                canFilter = false
                showFileRv = true
                showImageRv = false
                showVideoRv = false
                viewModel.loadAudio(::onCompleteRefresh)
            }

            "LARGE FILE" -> {
                canFilter = true
                showFileRv = true
                showImageRv = true
                showVideoRv = true
                viewModel.loadLargeFile(::onCompleteRefresh)
            }

            "EMPTY FILE" -> {
                canFilter = false
                showFileRv = true
                showImageRv = false
                showVideoRv = false
                viewModel.loadEmptyFile(::onCompleteRefresh)
            }

            "ZIP" -> {
                canFilter = false
                showFileRv = true
                showImageRv = false
                showVideoRv = false
                viewModel.loadZip(::onCompleteRefresh)
            }

            "APK" -> {
                canFilter = false
                showFileRv = true
                showImageRv = false
                showVideoRv = false
                viewModel.loadApk(::onCompleteRefresh)
            }

            "DOCUMENT" -> {
                canFilter = false
                showFileRv = true
                showImageRv = false
                showVideoRv = false
                viewModel.loadDocument(::onCompleteRefresh)
            }
        }

    }

    private fun initAdapter() {
        fileAdapter = SimpleListAdapter(this) { _, count ->
            fileSelectCount = count
            showItemsCount()
        }
        binding.rvFile.adapter = fileAdapter

        imagerAdapter = SimpleGridAdapter(isVideo = false, this, selectClick = { count ->
            imageSelectCount = count
            showItemsCount()
        }, itemClick = {})
        binding.rvImage.adapter = imagerAdapter

        videoAdapter = SimpleGridAdapter(isVideo = true, this, selectClick = { count ->
            videoSelectCount = count
            showItemsCount()
        }, itemClick = {})
        binding.rvVideo.adapter = videoAdapter

        binding.flFilter.setOnClickListener {
            showFilterPopupWindow()
        }

    }

    private fun showItemsCount() {

        fileSelectCount = fileAdapter.getSelectData().size
        imageSelectCount = imagerAdapter.getSelectData().size
        videoSelectCount = videoAdapter.getSelectData().size

        val count = fileSelectCount + imageSelectCount + videoSelectCount
        binding.tvItems.text = this.getString(R.string.select_d_items, count)
        if (count == 0) {
            binding.tvDelete.visibility = View.GONE
        } else {
            binding.tvDelete.visibility = View.VISIBLE
            binding.tvDelete.setOnClickListener {
                val selectData = arrayListOf<JoFileJo>()
                val selectFile =
                    if (binding.rvFile.isVisible) fileAdapter.getSelectData() else listOf()
                selectData.addAll(selectFile)
                val selectImage =
                    if (binding.rvImage.isVisible) imagerAdapter.getSelectData() else listOf()
                selectData.addAll(selectImage)
                val selectVideo =
                    if (binding.rvVideo.isVisible) videoAdapter.getSelectData() else listOf()
                selectData.addAll(selectVideo)
                viewModel.deleteFiles(selectData.map { it.toFile() }) {
                    lifecycleScope.launch(Dispatchers.Main) {
                        listData.removeAll(selectData.toSet())
                        onDeleteRefresh()
                    }
                }
            }
        }
    }

    private fun onDeleteRefresh() {
        if (listData.isNotEmpty()) {
            binding.tvItems.visibility = View.VISIBLE
            if (canFilter) {
                binding.flFilter.visibility = View.VISIBLE
            }
            binding.scrollContent.visibility = View.VISIBLE
            switchUi(true)
            showItemsCount()
        } else {
            binding.flEmpty.visibility = View.VISIBLE
            binding.tvItems.visibility = View.INVISIBLE
            binding.scrollContent.visibility = View.GONE
            binding.tvDelete.visibility = View.GONE
        }
    }

    private fun onCompleteRefresh(list: List<JoListFileJo>) =
        lifecycleScope.launch(Dispatchers.Main) {
            binding.pb.visibility = View.GONE
            if (list.isNotEmpty()) {
                binding.tvItems.visibility = View.VISIBLE
                listData = list as ArrayList<JoListFileJo>
                if (canFilter) {
                    binding.flFilter.visibility = View.VISIBLE
                }
                binding.scrollContent.visibility = View.VISIBLE
                switchUi(true)
            } else {
                binding.tvItems.visibility = View.INVISIBLE
                binding.flEmpty.visibility = View.VISIBLE
            }
        }

    private fun switchUi(isFirst: Boolean = false) {
        val imageFile = listData.filter { it.isImage() }
        val videoFile = listData.filter { it.isVideo() }
        val file = listData.filter { !it.isVideo() && !it.isImage() }
        val fileList = arrayListOf<JoListFileJo>()

        if (isFirst) {
            showFileRv = file.isNotEmpty()
            fileEnable = file.isNotEmpty()

            showImageRv = imageFile.isNotEmpty()
            imageEnable = imageFile.isNotEmpty()

            showVideoRv = videoFile.isNotEmpty()
            videoEnable = videoFile.isNotEmpty()
        }


        if (showImageRv) {
            binding.tvImage.visibility = View.VISIBLE
            binding.rvImage.visibility = View.VISIBLE
            imagerAdapter.setData(imageFile)
        } else {
            binding.tvImage.visibility = View.GONE
            binding.rvImage.visibility = View.GONE
        }

        if (showVideoRv) {
            binding.tvVideo.visibility = View.VISIBLE
            binding.rvVideo.visibility = View.VISIBLE
            videoAdapter.setData(videoFile)
        } else {
            binding.tvVideo.visibility = View.GONE
            binding.rvVideo.visibility = View.GONE
        }

        if (showFileRv) {
            binding.tvFile.visibility = View.VISIBLE
            binding.rvFile.visibility = View.VISIBLE
            fileList.addAll(file)
            if (!showImageRv) fileList.addAll(imageFile)
            if (!showVideoRv) fileList.addAll(videoFile)
            fileAdapter.setData(file)
        } else {
            binding.tvFile.visibility = View.GONE
            binding.rvFile.visibility = View.GONE
        }

        if (!showFileRv && !showVideoRv && !showImageRv) {
            binding.tvItems.visibility = View.GONE
        } else {
            binding.tvItems.visibility = View.VISIBLE
        }
    }

    @SuppressLint("ClickableViewAccessibility", "InflateParams")
    private fun showFilterPopupWindow() {
        val popupWindowView = layoutInflater.inflate(R.layout.popupwindow_file_filter, null)
        val popupBinding = PopupwindowFileFilterBinding.bind(popupWindowView)

        val width =
            resources.getDimensionPixelSize(R.dimen.dp_94)
        val height =
            resources.getDimensionPixelSize(R.dimen.dp_40)
        val margin =
            resources.getDimensionPixelSize(R.dimen.dp_10)
        var i = 0
        if (fileEnable) {
            i++
        }
        if (imageEnable) {
            i++
        }
        if (videoEnable) {
            i++
        }

        val popupWindow = PopupWindow(popupWindowView, width, height * i + margin, true)
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popupWindow.isOutsideTouchable = true
        popupWindow.isTouchable = true

        popupWindow.showAsDropDown(binding.ivFilter, 0, 0)

        popupBinding.tvFile.isSelected = showFileRv
        popupBinding.ivFile.isSelected = showFileRv

        popupBinding.tvImage.isSelected = showImageRv
        popupBinding.ivImage.isSelected = showImageRv

        popupBinding.tvVideo.isSelected = showVideoRv
        popupBinding.ivVideo.isSelected = showVideoRv

        if (fileEnable) {
            popupBinding.llFile.visibility = View.VISIBLE
            popupBinding.llFile.setOnClickListener {

                if (!showImageRv && !showVideoRv && showFileRv) return@setOnClickListener

                showFileRv = !showFileRv
                popupBinding.tvFile.isSelected = showFileRv
                popupBinding.ivFile.isSelected = showFileRv
                if (!showFileRv) {
                    fileAdapter.toggleSelect(false)
                }
                popupWindow.dismiss()
                switchUi()
                showItemsCount()
            }
        } else {
            popupBinding.llFile.visibility = View.GONE
        }

        if (imageEnable) {
            popupBinding.llImage.visibility = View.VISIBLE
            popupBinding.llImage.setOnClickListener {

                if (!showFileRv && !showVideoRv && showImageRv) return@setOnClickListener

                showImageRv = !showImageRv
                popupBinding.tvImage.isSelected = showImageRv
                popupBinding.ivImage.isSelected = showImageRv
                if (!showImageRv) {
                    imagerAdapter.toggleSelect(false)
                }
                popupWindow.dismiss()
                switchUi()
                showItemsCount()
            }
        } else {
            popupBinding.llImage.visibility = View.GONE
        }

        if (videoEnable) {
            popupBinding.llVideo.visibility = View.VISIBLE
            popupBinding.llVideo.setOnClickListener {

                if (!showFileRv && !showImageRv && showVideoRv) return@setOnClickListener

                showVideoRv = !showVideoRv
                popupBinding.tvVideo.isSelected = showVideoRv
                popupBinding.ivVideo.isSelected = showVideoRv
                if (!showVideoRv) {
                    videoAdapter.toggleSelect(false)
                }
                popupWindow.dismiss()
                switchUi()
                showItemsCount()
            }
        } else {
            popupBinding.llVideo.visibility = View.GONE
        }

    }

}