package com.remax.visualnovel.ui.main

import android.os.Build
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatImageView
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.ImmersionBar
import com.remax.visualnovel.R
import com.remax.visualnovel.app.base.BaseBindingActivity
import com.remax.visualnovel.databinding.ActivityMainBinding
import com.remax.visualnovel.event.model.OnLoginEvent
import com.remax.visualnovel.event.model.tab.ContactTab
import com.remax.visualnovel.event.model.tab.MainTab
import com.remax.visualnovel.event.model.tab.OnTabChangedEvent
import com.remax.visualnovel.extension.launchWithRequest
import com.remax.visualnovel.extension.setMargin
import com.remax.visualnovel.extension.setOnClick
import com.remax.visualnovel.extension.toast
import com.remax.visualnovel.manager.login.LoginManager
import com.remax.visualnovel.utils.Routers
import com.remax.visualnovel.utils.StatusBarUtils
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import com.pengxr.modular.eventbus.generated.events.EventDefineOfUIEvents
import com.pengxr.modular.eventbus.generated.events.EventDefineOfUserEvents
import com.remax.visualnovel.ui.main.actor.ActorListFragment
import com.remax.visualnovel.ui.main.book.BookListFragment
import com.remax.visualnovel.ui.main.history.HistoryFragment
import com.remax.visualnovel.ui.main.managa.MangaListFragment
import dagger.hilt.android.AndroidEntryPoint



@AndroidEntryPoint
@Route(path = Routers.MAIN)
class MainActivity : BaseBindingActivity<ActivityMainBinding>() {

    private val mainViewModel by viewModels<MainViewModel>()

    override fun initView() {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarColor(R.color.transparent)
            .statusBarDarkFont(true)
            .fitsSystemWindows(true)
            .init();

        onBackPressedDispatcher.addCallback(this) {
            if (mainViewModel.canBack) {
                finish()
            } else {
                toast(getString(R.string.close_app_hint))
                mainViewModel.startCanBackTimer()
            }
        }

        with(binding) {
            with(viewPager2) {
                setMargin(topMargin = StatusBarUtils.statusBarHeight)

                val fragments = listOf(
                    BookListFragment.newInstance(),
                    MangaListFragment.newInstance(),
                    ActorListFragment.newInstance(),
                    HistoryFragment.newInstance()
                )

                offscreenPageLimit = fragments.size
                isUserInputEnabled = false
                adapter = object : FragmentStateAdapter(this@MainActivity) {
                    override fun getItemCount() = fragments.size
                    override fun createFragment(position: Int): Fragment = fragments[position]
                }
            }

            changeViewPagerIndex(MainTab.TAB_BOOKS)
            setOnClick(bookItem, mangaItem, actorItem, historyItem) {
                when (this) {
                    bookItem -> changeViewPagerIndex(MainTab.TAB_BOOKS)
                    mangaItem -> changeViewPagerIndex(MainTab.TAB_MANGAS)
                    actorItem -> changeViewPagerIndex(MainTab.TAB_ACTORS)
                    historyItem -> changeViewPagerIndex(MainTab.TAB_HISTORY)
                }
            }
        }
    }

    override fun initData() {
        refreshBaseInfo()
        launchWithRequest({
            // TODO load init datas by model
            //mainViewModel.getAllRole(true)
        })
        loginNim()
        //chkScheme(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventDefineOfUserEvents.onLoginStatusChanged().removeObserver(loginObserver)
    }

    private val loginObserver = androidx.lifecycle.Observer<OnLoginEvent?> {
        if (it?.isLogin() == true) {
            loginNim()
            checkRegister()
        }
        launchWithRequest({
            //mainViewModel.getAllRole(true)
        })
    }

    override fun subscribeUi() {

    }



    /**
     * 新建账号需要完善信息
     */
    private fun checkRegister() {
        if (LoginManager.user?.cpUserInfo == true) {
            Routers.navigation(Routers.REGISTER)
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                XXPermissions.with(this).permission(PermissionLists.getPostNotificationsPermission()).request(null)
            }
        }
    }

    private fun refreshBaseInfo() {
        if (LoginManager.isLogin) {
            launchWithRequest({
                mainViewModel.getMyBaseInfo()
            })
        }
    }

    /**
     * 登录网易云信
     */
    private fun loginNim() {
        /*launchAndCollect({
            mainViewModel.getNimInfo()
        }) {
            onSuccess = {
                it?.run {
                    NimManager.login(this)
                }
                LoginManager.refreshUnreadCount()
            }
        }
        launchWithRequest(mainViewModel::getNimInfo)*/
    }



    private fun changeViewPagerIndex(positionTab: MainTab) {
        var go = positionTab.checkLogin
        if (go) {
            LoginManager.checkLogin {
                go = false
            }
        }
        if (go) return

        binding.run {
            viewPager2.setCurrentItem(positionTab.index, false)

            val tabItemUIList = listOf(
                Pair(
                    MainTab.TAB_BOOKS,
                    TabItemUI(bookItem, R.mipmap.main_tab_book_on, R.mipmap.main_tab_book_off)
                ),
                Pair(
                    MainTab.TAB_MANGAS,
                    TabItemUI(mangaItem, R.mipmap.main_tab_manga_on, R.mipmap.main_tab_manga_off)
                ),
                Pair(
                    MainTab.TAB_ACTORS,
                    TabItemUI(actorItem, R.mipmap.main_tab_actor_on, R.mipmap.main_tab_actor_off)
                ),
                Pair(MainTab.TAB_HISTORY,
                    TabItemUI(historyItem, R.mipmap.main_tab_history_on, R.mipmap.main_tab_history_off))
            )

            tabItemUIList.forEach {
                if (it.first.index == positionTab.index) {
                    it.second.item.setImageResource(it.second.selectRes)
                } else {
                    it.second.item.setImageResource(it.second.unselectRes)
                }
            }
        }


    }

    companion object {
        fun start(jumpItem: MainTab = MainTab.TAB_BOOKS, chatItem: ContactTab? = null) {
            fun go() {
                Routers.navigation(Routers.MAIN)
                EventDefineOfUIEvents.onHomeTabChanged().post(OnTabChangedEvent(jumpItem, chatItem))
            }
            // chat和me的tab需要检查登录权限
            if (jumpItem.checkLogin) {
                LoginManager.checkLogin {
                    go()
                }
            } else {
                go()
            }
        }
    }

    data class TabItemUI(
        val item: AppCompatImageView,
        @DrawableRes val selectRes: Int,
        @DrawableRes val unselectRes: Int,
    )
}