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.isVisible
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.browserwhite.databinding.ActivityBookmarkBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.utils.BarUtils

class BookmarkActivity : BaseActivity<ActivityBookmarkBinding>() {

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


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

    private val bookmarkFragment: BookmarkFragment by lazy {
        BookmarkFragment()
    }
    private val historyFragment: HistoryFragment by lazy {
        HistoryFragment()
    }

    private val fragments by lazy {
        mutableListOf(bookmarkFragment, historyFragment)
    }

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

        binding.viewPager2.run {
            adapter = object : FragmentStateAdapter(this@BookmarkActivity) {
                override fun getItemCount(): Int {
                    return fragments.size
                }

                override fun createFragment(position: Int): Fragment {
                    return fragments[position]
                }
            }
        }

        binding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                noSelectUI()
                if (position == 0) {
                    changeBookmark()
                } else {
                    changeHistory()
                }
            }
        })
    }

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

        binding.tvTabBookmark.setOnClickListener {
            if (binding.tvTabBookmark.isSelected) {
                return@setOnClickListener
            }
            binding.viewPager2.currentItem = 0
        }

        binding.tvTabHistory.setOnClickListener {
            if (binding.tvTabHistory.isSelected) {
                return@setOnClickListener
            }
            binding.viewPager2.currentItem = 1
        }
        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()
//            }
        }
    }


    private fun changeBookmark() {
        binding.tvTabBookmark.isSelected = true
        binding.tvTabHistory.isSelected = false
        binding.ivNewFolder.isVisible = true
        binding.ivDelete.isVisible = false
        currentTab = BOOKMARK_TAB
    }

    private fun changeHistory() {
        binding.tvTabHistory.isSelected = true
        binding.tvTabBookmark.isSelected = false
        binding.ivNewFolder.isVisible = false
        binding.ivDelete.isVisible = true
        currentTab = HISTORY_TAB
    }

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


    @SuppressLint("NotifyDataSetChanged")
    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
        bookmarkFragment.bookmarkAdapter.showSelector = true
        bookmarkFragment.bookmarkAdapter.items.forEach { it.isSelect = false }
        bookmarkFragment.bookmarkAdapter.notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    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
        bookmarkFragment.bookmarkAdapter.showSelector = false
        bookmarkFragment.bookmarkAdapter.notifyDataSetChanged()
    }

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


//        bookmarkAdapter = BookmarkAdapter()
//        bookmarkAdapter.changeFolderAction = { folderId ->
//            val list = bookmarkList.filter { it.folderId == folderId }
//            binding.llEmpty.isVisible = list.isEmpty()
//            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()
//                }
//            )
//        }


//    private fun initHistoryData() {
//        historyList.clear()
//        val list = SpBeanUtils.getSpBeanList(HISTORY_SP_KEY)
//        val gson = Gson()
//        val item = list.map { gson.fromJson(it, HistoryBean::class.java) }
//
//        val time = ""
//        item.sortedBy { it.time }.forEach {
//            if (time != it.time.toFormatTime()) {
//                it.showTime = true
//            }
//            historyList.add(it)
//        }
//    }

//    private fun initBookmarkData() {
//        bookmarkList.clear()
//        val list = SpBeanUtils.getSpBeanList(BOOKMARK_SP_KEY)
//        val gson = Gson()
//        val items = list.map { gson.fromJson(it, BookmarkBean::class.java) }
//
//        bookmarkList.addAll(items)
//        bookmarkAdapter.currentFolderId = 0
//        bookmarkAdapter.submitList(bookmarkList.filter { it.folderId == bookmarkAdapter.currentFolderId })
//        binding.llEmpty.isVisible = items.isEmpty()
//    }

}