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.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.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_SP_KEY
import com.base.browserwhite.utils.SpBeanUtils.HISTORY_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 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()
                }
            }
        })

//        val page = intent.extras?.getInt("page", 0) ?: 0
//        binding.viewPager2.currentItem = page
    }

    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 {

            if (currentTab == BOOKMARK_TAB) {
                val selectList = bookmarkFragment.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)
                    }
                    bookmarkFragment.initData()
                    noSelectUI()
                }
            }


        }

        binding.ivDelete.setOnClickListener {
            if (currentTab == HISTORY_TAB) {
                showDeleteTipDialog(desc = "Clear all browsing history?") {
                    SpBeanUtils.clearSpBean(HISTORY_SP_KEY)
                    historyFragment.initData()
                }
            }
        }
    }


    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()
        if (currentTab == BOOKMARK_TAB) {
            bookmarkFragment.initData()
        } else {
            historyFragment.initData()
        }
    }


    @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"
    }
}