package com.zxhy.hfilemanagermaster.internalstorage

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.KeyEvent
import android.view.KeyEvent.ACTION_UP
import android.view.MotionEvent
import android.view.View
import android.widget.PopupWindow
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ReportFragment.Companion.reportFragment
import androidx.lifecycle.lifecycleScope
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ActivityInternalStorageBinding
import com.example.hfilemanagermaster.databinding.PopupwindowMoreOperationBinding
import com.zxhy.hfilemanagermaster.data.MediaDataC
import com.zxhy.hfilemanagermaster.data.file2MediaDataC
import com.zxhy.hfilemanagermaster.dialog.showFileNameDialog
import com.zxhy.hfilemanagermaster.dialog.showOperationDialog
import com.zxhy.hfilemanagermaster.knife.Saf
import com.zxhy.hfilemanagermaster.knife.toast
import com.zxhy.hfilemanagermaster.permission.IntentLauncher
import com.zxhy.hfilemanagermaster.permission.PermissionLauncher
import com.zxhy.hfilemanagermaster.permission.requestStoreFollow
import com.zxhy.hfilemanagermaster.permission.settingManageExternalStorage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

// 额外储存管理权限，读几个图片和视频
@SuppressLint("SetTextI18n")
class InternalStorageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityInternalStorageBinding
    private lateinit var saf: Saf
    private lateinit var intentLauncher: IntentLauncher
    private lateinit var permissionLauncher: PermissionLauncher
    private lateinit var fileAdapter: FileAdapter
    private val browseMode = 0
    private val selectMode = 1
    private val selectedOperationMode = 2
    private var currentMode = browseMode //0普通浏览模式  1可选模式  2选中操作模式
    private var popupWindow: PopupWindow? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        saf = Saf(this)
        intentLauncher = IntentLauncher(this)
        binding = ActivityInternalStorageBinding.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
        }
        window.statusBarColor = ContextCompat.getColor(this, R.color.color_C2F300)
        binding.ivArrow.setOnClickListener {
            finish()
        }
        binding.tvSet.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (!Environment.isExternalStorageManager()) {
                    val uri = Uri.parse("package:$packageName")
                    val intent = settingManageExternalStorage(uri)
                    intentLauncher.launch(intent) {
                        val flag = Environment.isExternalStorageManager()
                        if (flag) {
                            fileMode()
//                            toast("已设置额外储存管理")
                        } else {
//                            toast("未设置额外储存管理")
                            lockMode()
                        }
                    }
                } else {
//                    toast("已设置额外储存管理")
                    fileMode()
                }
            } else {
                requestStoreFollow(permissionLauncher, intentLauncher) { fileMode() }
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                fileMode()
            } else {
                lockMode()
            }
        } else {
            fileMode()
        }
    }

    private fun fileMode() {
        binding.clLock.visibility = View.GONE
        binding.clShow.visibility = View.VISIBLE
        fileAdapter = FileAdapter {
            binding.ivAll.isSelected = it
        }
        binding.ivAll.setOnClickListener {
            it.isSelected = fileAdapter.setToggleSelect()
        }
        binding.rv.adapter = fileAdapter
        File("").renameTo(File(""))
        loadFile()

        browseMode()
    }

    private fun loadFile() {
        lifecycleScope.launch(Dispatchers.IO) {
            val rootList = Environment.getExternalStorageDirectory().listFiles()
            val list = rootList?.map {
                it.file2MediaDataC(this@InternalStorageActivity)
            } ?: listOf()

            lifecycleScope.launch(Dispatchers.Main) {
                fileAdapter.setData(list)
            }
        }
    }

    private fun lockMode() {
        binding.clLock.visibility = View.VISIBLE
        binding.clShow.visibility = View.GONE

        binding.ivAll.visibility = View.GONE
        binding.tvAll.visibility = View.GONE
        binding.ivWrite.visibility = View.GONE
        binding.ivNewFolder.visibility = View.GONE

    }

    //可选择模式
    private fun selectMode() {
        currentMode = selectMode
        binding.ivWrite.visibility = View.GONE
        binding.ivNewFolder.visibility = View.VISIBLE

        binding.ivAll.visibility = View.VISIBLE
        binding.tvAll.visibility = View.VISIBLE

        binding.clOperation.visibility = View.VISIBLE
        binding.clConfirm.visibility = View.GONE

        binding.ivMove.setOnClickListener {
            val selectList = fileAdapter.getSelectFile()
            if (selectList.isEmpty()) return@setOnClickListener
            fileAdapter.showNoSelect()
            moveOperation(selectList)
        }
        binding.ivCopy.setOnClickListener {
            val selectList = fileAdapter.getSelectFile()
            if (selectList.isEmpty()) return@setOnClickListener
            fileAdapter.showNoSelect()
            copyOperation(selectList)
        }
        binding.ivShare.setOnClickListener {
            this.toast("Stay tuned!")
        }
        binding.ivMore.setOnClickListener {
            showPopupMoreOperation()
        }
    }

    //普通浏览模式
    private fun browseMode() {
        currentMode = browseMode
        binding.ivWrite.visibility = View.VISIBLE
        binding.ivNewFolder.visibility = View.VISIBLE

        binding.ivAll.visibility = View.GONE
        binding.tvAll.visibility = View.GONE

        binding.clOperation.visibility = View.GONE

        binding.ivWrite.setOnClickListener {
            fileAdapter.showSelect()
            selectMode()
        }
    }

    private fun moveOperation(selectList: List<MediaDataC>) {
        currentMode = selectedOperationMode
        binding.clOperation.visibility = View.INVISIBLE
        binding.clConfirm.visibility = View.VISIBLE
        binding.tvDefine.text = "Motion"
        binding.tvCancel.setOnClickListener {
            selectMode()
        }
        binding.tvDefine.setOnClickListener {
            val dir = fileAdapter.getCurrentDir()
            if (dir == null) {
                this.toast("motion failed ")
            } else {
                moveFile(selectList, dir)
            }
        }
    }

    private fun copyOperation(selectList: List<MediaDataC>) {
        currentMode = selectedOperationMode
        binding.clOperation.visibility = View.INVISIBLE
        binding.clConfirm.visibility = View.VISIBLE
        binding.tvDefine.text = "Copy"
        binding.tvCancel.setOnClickListener {
            selectMode()
        }
        binding.tvDefine.setOnClickListener {
            val dir = fileAdapter.getCurrentDir()
            if (dir == null) {
                this.toast("copy failed ")
            } else {
                copyFile(selectList, dir)
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun moveFile(selectList: List<MediaDataC>, dir: File) = Thread {

        try {
            selectList.forEach {
                val file = File(it.path)
                val fileName = file.name
                if (file.exists()) {
                    file.copyTo(File(dir, fileName))
                    file.delete()
                }
            }
            runOnUiThread {
//                this.toast("motion success!")
                showOperationDialog(R.mipmap.er_89875, "motion success!") {
                    fileAdapter.notifyCurrentDir(this)
                }
            }
        } catch (e: Exception) {
            runOnUiThread { this.toast("motion failed ") }
        } finally {
            runOnUiThread { browseMode() }
        }
    }.start()

    private fun copyFile(selectList: List<MediaDataC>, dir: File) = Thread {
        try {
            selectList.forEach {
                val file = File(it.path)
                val fileName = file.name
                if (file.exists()) {
                    file.copyTo(File(dir, fileName))
                }
            }
            runOnUiThread {
//                this.toast("copy success! ")
                showOperationDialog(R.mipmap.qw_8796, "copy success!") {
                    fileAdapter.notifyCurrentDir(this)
                }
            }
        } catch (e: Exception) {
            runOnUiThread { this.toast("copy failed ") }
        } finally {
            runOnUiThread {
                browseMode()
            }
        }
    }.start()


    @SuppressLint("ClickableViewAccessibility")
    private fun showPopupMoreOperation() {
        val yOff = resources.getDimensionPixelSize(R.dimen.dp_180)

        if (popupWindow == null) {
            val popupWindowView = layoutInflater.inflate(R.layout.popupwindow_more_operation, null)
            val popupBinding = PopupwindowMoreOperationBinding.bind(popupWindowView)
            val width =
                resources.getDimensionPixelSize(R.dimen.dp_150)
            val height =
                resources.getDimensionPixelSize(R.dimen.dp_125)
            popupWindow = PopupWindow(popupWindowView, width, height, true)
            popupWindow?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            popupWindow?.isOutsideTouchable = true
            popupWindow?.isTouchable = true
            popupWindow?.showAsDropDown(binding.ivPlaceholder, 0, -yOff)

            popupBinding.apply {
                tvRename.setOnTouchListener { v, event ->

                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            popupBinding.ivRename.isSelected = true
                        }

                        MotionEvent.ACTION_UP -> {
                            popupBinding.ivRename.isSelected = false
                        }

                        else -> {}
                    }
                    false
                }
                tvRename.setOnClickListener {
                    val list = fileAdapter.getSelectFile()
                    if (list.size == 1) {
                        val file = File(list.first().path)
                        renameFile(file)
                        popupWindow?.dismiss()
                    } else {
                        toast("Please select only one file!")
                    }
                }
                tvDelete.setOnTouchListener { v, event ->
                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            popupBinding.ivDelete.isSelected = true
                        }

                        MotionEvent.ACTION_UP -> {
                            popupBinding.ivDelete.isSelected = false
                        }

                        else -> {}
                    }
                    false
                }
                tvDetails.setOnTouchListener { v, event ->
                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            popupBinding.ivDetails.isSelected = true
                        }

                        MotionEvent.ACTION_UP -> {
                            popupBinding.ivDetails.isSelected = false
                        }

                        else -> {}
                    }
                    false
                }
            }
        } else {
            popupWindow?.showAsDropDown(binding.ivPlaceholder, 0, -yOff)
        }
    }

    private fun renameFile(file: File) {
        val dir = file.parentFile ?: File("")
        if (file.exists() && dir.exists()) {
            showFileNameDialog("Rename", sureAction = {
                try {
                    file.renameTo(File(dir, it))
                } catch (e: Exception) {
                    e.printStackTrace()
                    toast("Can't rename file!")
                }
                fileAdapter.notifyCurrentDir(this)
            }, dismissAction = {})
        } else {
            toast("Can't rename file!")
        }

    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {

        when (currentMode) {
            selectedOperationMode -> {
                var flag = false
                if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == ACTION_UP) {
                    flag = fileAdapter.beforePage(this)
                }
                return if (flag) {
                    false
                } else {
                    super.dispatchKeyEvent(event)
                }
            }

            selectMode -> {
                browseMode()
                fileAdapter.showNoSelect()
                return false
            }

            browseMode -> {
                var flag = false
                if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == ACTION_UP) {
                    flag = fileAdapter.beforePage(this)
                }
                return if (flag) {
                    false
                } else {
                    super.dispatchKeyEvent(event)
                }
            }
        }

        return super.dispatchKeyEvent(event)

    }

}