package com.base.browserwhite.ui.activity.bookmark

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.browserwhite.bean.BookmarkBean
import com.base.browserwhite.databinding.ActivityBookmarkBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.activity.bookmark.BookmarkFolderActivity.Companion.selectFolder
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.ui.views.BookmarkDialog.showBookmarkMoreDialog
import com.base.browserwhite.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_NAV_SP_KEY
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_SP_KEY
import com.base.browserwhite.utils.ToastUtils.toast
import com.google.gson.Gson

class BookmarkActivity : BaseActivity<ActivityBookmarkBinding>() {

    private val TAG = "BookmarkActivity"
    private var currentTab = BOOKMARK_TAB


    override val binding: ActivityBookmarkBinding by lazy {
        ActivityBookmarkBinding.inflate(layoutInflater)
    }

    private lateinit var bookmarkAdapter: BookmarkAdapter

    private val bookmarkList = arrayListOf<BookmarkBean>()

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        bookmarkAdapter = BookmarkAdapter()
        bookmarkAdapter.changeFolderAction = { folderId ->
            val list = bookmarkList.filter { it.folderId == folderId }
            bookmarkAdapter.submitList(list)
        }
        bookmarkAdapter.moreAction = { view, bean ->
            showBookmarkMoreDialog(
                view,
                bean.isFolder,
                //新开
                openNewTab = {
                    startActivity(Intent(this, WebBrowserActivity::class.java).apply {
                        putExtra("url", bean.url)
                    })
                },
                //删除
                deleteAction = {
                    if (bean.isFolder) {//书签目录
                        val desc = "Delete folder [${bean.name}] and the bookmarks in the folder?"
                        showDeleteTipDialog(desc) {
                            //删除书签目录
                            SpBeanUtils.deleteSpBeanCondition(BOOKMARK_SP_KEY, bean.id)
                            bookmarkList.remove(bean)
                            bookmarkAdapter.remove(bean)

                            //删除目录下书签
                            val subBeanList = bookmarkList.filter { it.folder == bean.name }
                            subBeanList.forEach { subBean ->
                                SpBeanUtils.deleteSpBeanCondition(BOOKMARK_SP_KEY, subBean.id)
                                bookmarkList.remove(subBean)
                                //删除书签导航
                                SpBeanUtils.deleteSpBeanCondition(BOOKMARK_NAV_SP_KEY, bean.id)
                            }
                        }
                    } else {//书签直接删除
                        SpBeanUtils.deleteSpBeanCondition(BOOKMARK_SP_KEY, bean.id)
                        bookmarkList.remove(bean)
                        bookmarkAdapter.remove(bean)
                        //删除书签导航
                        SpBeanUtils.deleteSpBeanCondition(BOOKMARK_NAV_SP_KEY, bean.id)
                    }
                },
                //编辑
                editAction = {
                    BookmarkFolderEditActivity.editFolder = bean
                    launcher.launch(Intent(Intent(this, BookmarkFolderEditActivity::class.java)))
                },
                //添加导航
                addNavAction = {
                    SpBeanUtils.addSpBean(BOOKMARK_NAV_SP_KEY, bean)
                },
                //选择
                selectAction = {
                    selectUI()
                }
            )
        }

        changeBookmark()
    }

    private fun changeBookmark() {
        binding.rv.adapter = bookmarkAdapter
        bookmarkAdapter.submitList(bookmarkList)
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initData() {
        initBookmarkData()
    }

    private fun initBookmarkData() {
        bookmarkList.clear()
        val list = SpBeanUtils.getSpBeanList(BOOKMARK_SP_KEY)
        val items = list.map { Gson().fromJson(it, BookmarkBean::class.java) }

        bookmarkList.addAll(items)
        bookmarkAdapter.currentFolderId = 0
        bookmarkAdapter.submitList(bookmarkList.filter { it.folderId == bookmarkAdapter.currentFolderId })
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (currentTab == BOOKMARK_TAB) {
                if (bookmarkAdapter.canBeforeFolder()) {
                    bookmarkAdapter.beforeFolder()
                } else {
                    finishToMain()
                }
            } else {
                finishToMain()
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.tvTabBookmark.setOnClickListener {
            if (binding.tvTabBookmark.isSelected) {
                return@setOnClickListener
            }
            binding.tvTabBookmark.isSelected = true
            binding.tvTabHistory.isSelected = false
            currentTab = BOOKMARK_TAB
        }
        binding.tvTabBookmark.callOnClick()

        binding.tvTabHistory.setOnClickListener {
            if (binding.tvTabHistory.isSelected) {
                return@setOnClickListener
            }
            binding.tvTabHistory.isSelected = true
            binding.tvTabBookmark.isSelected = false
            currentTab = HISTORY_TAB
        }
        binding.ivNewFolder.setOnClickListener {
            launcher.launch(Intent(this, BookmarkFolderEditActivity::class.java))
        }
        binding.tvCancel.setOnClickListener { noSelectUI() }
        binding.llRemoveFolder.setOnClickListener {
            val selectList = bookmarkAdapter.items.filter { it.isSelect }
            if (selectList.isEmpty()) {
                toast("Please select a bookmark to move")
                return@setOnClickListener
            }
            if (selectList.any { it.isFolder }) {
                toast("Folder cannot be moved")
                return@setOnClickListener
            }
            selectFolder = selectList.first().folder
            launcher.launch(Intent(this, BookmarkFolderActivity::class.java)) {
                val json = it.data?.extras?.getString("Folder")
                val folder = Gson().fromJson(json, BookmarkBean::class.java)
                selectList.forEach { bookmarkBean ->
                    bookmarkBean.folderId = folder.id
                    bookmarkBean.folder = folder.name
                    SpBeanUtils.editSpBean(BOOKMARK_SP_KEY, bookmarkBean)
                }
                initBookmarkData()
                noSelectUI()
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun selectUI() {
        binding.flFanhui.visibility = View.GONE
        binding.flTab.visibility = View.GONE
        binding.tvCancel.visibility = View.VISIBLE
        binding.ivNewFolder.visibility = View.GONE
        binding.flOperation.visibility = View.VISIBLE
        bookmarkAdapter.showSelector = true
        bookmarkAdapter.items.forEach { it.isSelect = false }
        bookmarkAdapter.notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun noSelectUI() {
        binding.tvCancel.visibility = View.GONE
        binding.flFanhui.visibility = View.VISIBLE
        binding.flTab.visibility = View.VISIBLE
        binding.ivNewFolder.visibility = View.VISIBLE
        binding.flOperation.visibility = View.GONE
        bookmarkAdapter.showSelector = false
        bookmarkAdapter.notifyDataSetChanged()
    }

    companion object {
        private val BOOKMARK_TAB = "bookmark_tab"
        private val HISTORY_TAB = "history_tab"
    }

}