package com.base.locationsharewhite.ui.main

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.locationsharewhite.R
import com.base.locationsharewhite.ads.AdsMgr
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.bean.ViewerBean
import com.base.locationsharewhite.databinding.ActivityLocationShareBinding
import com.base.locationsharewhite.fcm.NotificationUiUtil.sendAllAllowedNotification
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.location.LocationShareListUtils
import com.base.locationsharewhite.location.LocationShareUtils
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_FAILED
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_MYSELF
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_SHARED
import com.base.locationsharewhite.location.LocationShareUtils.SHARE_STATE_SUCCESS
import com.base.locationsharewhite.location.LocationStatusUtils
import com.base.locationsharewhite.service.StayJobService.Companion.requestServiceLocationUpdates
import com.base.locationsharewhite.ui.set.RenameActivity
import com.base.locationsharewhite.ui.views.DialogView.showViewerMoreDialog
import com.base.locationsharewhite.ui.views.LocationPermissionDialog.showLocationAllowAllTimeDialog
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.LogEx
import com.base.locationsharewhite.utils.PermissionUtils.checkAllLocationPermission
import com.base.locationsharewhite.utils.PermissionUtils.requestLocationAllowAllTime
import com.base.locationsharewhite.utils.SpStringUtils
import com.base.locationsharewhite.utils.SpStringUtils.VIEWER_NICKNAME_KEY
import com.base.locationsharewhite.utils.SpStringUtils._DEVICE_NICKNAME_
import com.base.locationsharewhite.utils.ToastUtils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * 添加谁可以看我
 */
class LocationShareActivity : BaseActivity<ActivityLocationShareBinding>() {

    override val binding: ActivityLocationShareBinding by lazy {
        ActivityLocationShareBinding.inflate(layoutInflater)
    }
    private lateinit var adapter: ViewerAdapter


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

        val recreated = changeLanguage(this)
        if (recreated) return

        if (AdsMgr.adsConfigBean.functionInShowAd) {
            AdsMgr.showInsert(this, showCallBack = object : AdsShowCallBack() {
                override fun close(where: Int) {

                }

                override fun failed(where: Int) {
                }

                override fun googleFailed(where: Int) {
                }
            })
        }
        binding.editCode.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                binding.editCode.hint = ""
            } else {
                binding.editCode.hint = this.resources.getString(R.string.enter_others_location_code)
            }
        }

        binding.shimmerLayout.startShimmerAnimation()
        adapter = ViewerAdapter(switchAction = { item, isChecked ->
            val changeStatus = if (isChecked) 1 else 0
            LogEx.logDebug(TAG, "device=${item.device}")
            LocationStatusUtils.changeViewerStatus(item.device, changeStatus) { flag ->
                runOnUiThread {
                    if (flag) {
                        item.status = changeStatus
                    }
                    adapter.notifyDataSetChanged()
                }
            }
        })
        adapter.moreAction = { anchorView, viewerBean ->
            showViewerMoreDialog(anchorView, deleteAction = {
                LocationShareListUtils.deleteShare(viewerBean.device) {
                    runOnUiThread {
                        toast(it.toString(), true)
                    }
                    initShareData()
                }
            }, renameAction = {
                startActivity(Intent(this, RenameActivity::class.java).apply {
                    putExtra("doWhat", RenameActivity.RENAME_VIEWER_NICK_NAME)
                    putExtra("device", viewerBean.device)
                    putExtra("nickName", viewerBean.localNickName ?: viewerBean.nickName)
                })
            })
        }
        binding.rv.adapter = adapter

        initShareData()
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val recreated = changeLanguage(this)
        if (recreated) return
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdsMgr.adsConfigBean.functionBackShowAd) {
                AdsMgr.showInsert(this@LocationShareActivity, false, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        finishToMain()
                    }

                    override fun failed(where: Int) {
                        finishToMain()
                    }

                    override fun googleFailed(where: Int) {
                        finishToMain()
                    }
                })
            } else {
                finishToMain()
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvShare.setOnClickListener {

            val code = binding.editCode.text.toString()
            if (code.isEmpty()) {
                toast("code is empty", true)
                return@setOnClickListener
            }

            if (!checkAllLocationPermission()) {
                showAllowAllTimeDialog()
                return@setOnClickListener
            }

            hideKeyBoard()
            AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    shareLocationCode(code)
                }

                override fun failed(where: Int) {
                    shareLocationCode(code)
                }

                override fun googleFailed(where: Int) {
                    shareLocationCode(code)
                }

            })
        }
    }

    private fun hideKeyBoard() {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        if (currentFocus != null) {
            imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
        }
        binding.editCode.clearFocus()
    }

    private fun shareLocationCode(code: String) {
        LocationShareUtils.shareMyLocationByInvitationCode(code) { status ->
            LogEx.logDebug(TAG, "status=$status")
            runOnUiThread {
                when (status) {
                    SHARE_STATE_FAILED -> {
                        toast("Code verification failed", true)
                    }

                    SHARE_STATE_SUCCESS -> {
                        toast("Code verification success", true)
                        initShareData()
                    }

                    SHARE_STATE_SHARED -> {
                        toast("Sharing code has been added", true)
                    }

                    SHARE_STATE_MYSELF -> {
                        toast("Sharing code is yourself code", true)
                    }
                }

            }
        }
    }

    private fun initShareData() {
        LocationShareListUtils.getShareList(viewerListCallBack = {
            val nickList = SpStringUtils.getSpStringList(VIEWER_NICKNAME_KEY)
            it.forEach { viewer -> changeLocalNickName(viewer, nickList) }
            runOnUiThread {
                if (it.isEmpty()) {
                    binding.flBanner.visibility = View.GONE
                    binding.rv.visibility = View.GONE
                    binding.flAd.visibility = View.VISIBLE
                    AdsMgr.showNative(binding.flAd, R.layout.layout_admob_app_exit)
                } else {
                    binding.flAd.visibility = View.GONE
                    binding.flBanner.visibility = View.VISIBLE
                    binding.rv.visibility = View.VISIBLE
                    AdsMgr.showBanner(binding.flBanner, false)
                    adapter.submitList(it)
                }
            }
        })
    }

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

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshNickName() = lifecycleScope.launch(Dispatchers.IO) {
        val nickList = SpStringUtils.getSpStringList(VIEWER_NICKNAME_KEY)

        adapter.items.map { viewer ->
            changeLocalNickName(viewer, nickList)
        }
        launch(Dispatchers.Main) {
            adapter.notifyDataSetChanged()
        }
    }

    private fun changeLocalNickName(viewer: ViewerBean, nickList: List<String>) {
        val deviceNicknameSp = nickList.find { it.contains(viewer.device) }
        deviceNicknameSp?.let { sp ->
            runCatching {
                val localNickName = sp.split(_DEVICE_NICKNAME_)[1]
                viewer.localNickName = localNickName
            }
        }
    }

    private var allowAllTimeDialog: Dialog? = null
    private fun showAllowAllTimeDialog() {
        if (!checkAllLocationPermission()) {
//            toast("显示权限始终允许弹窗")
            if (allowAllTimeDialog == null) {
                allowAllTimeDialog =
                    showLocationAllowAllTimeDialog(
                        setAction = {
                            sendAllAllowedNotification(this)
                            requestLocationAllowAllTime(launcher, jumpOutAction = {
                                LogEx.logDebug(TAG, "jumpOutAction")
                            }, permissionAllowCallBack = {})
                        },
                        dismissAction = {
                            allowAllTimeDialog = null
                        })
            }
        } else {
//            toast("不显示权限始终允许弹窗")
            allowAllTimeDialog?.dismiss()
            allowAllTimeDialog = null

            requestServiceLocationUpdates()
        }
    }


}