package com.base.datarecovery.activity

import android.Manifest
import android.app.NotificationManager
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.provider.Settings
import android.view.View
import androidx.activity.addCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.datarecovery.ads.admob.AdmobBannerUtils
import com.base.datarecovery.databinding.ActivityMainBinding
import com.base.datarecovery.fragment.HomeFragment
import com.base.datarecovery.fragment.RecoveryFragment
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.utils.AppPreferences
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.view.DialogViews.showExitDialog
import com.base.datarecovery.view.NotifPermisonPop
import com.base.datarecovery.view.PermissionDialog.showPermissionBottomSheet
import com.base.datarecovery.view.RateStarPop.showRateStarPopDialog
import com.facebook.appevents.AppEventsLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : BaseActivity<ActivityMainBinding>() {
    private val requestPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (!it) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val intent = Intent()
                    intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                    intent.putExtra(Settings.EXTRA_APP_PACKAGE, this.packageName)
                    startActivity(intent)
                }
            }

        }
    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    private val homeFragment by lazy {
        HomeFragment()
    }
    private val recoveryFragment by lazy {
        RecoveryFragment()
    }

    private val fragments by lazy {
        mutableListOf(homeFragment, recoveryFragment)
    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        if (!checkStorePermission()) {
            if (dialog == null) {
                dialog = showPermissionBottomSheet(launcher) {
                    binding.flBanner.visibility = View.VISIBLE
                    AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flBanner)
                }
            }
        } else {
            binding.flBanner.visibility = View.VISIBLE
            AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flBanner)
        }
        binding.viewpager2.run {
            adapter = object : FragmentStateAdapter(this@MainActivity) {
                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) {
                setPageIndicate(position)
            }
        })


        val fbhome = AppPreferences.getInstance().getInt("fb_home", 0)
        if (fbhome == 0) {
            val logger = AppEventsLogger.newLogger(this)
            logger.logEvent("home")
            AppPreferences.getInstance().put("fb_home", 1)
        }
        if (!requestNotifPermisson()) {
            NotifPermisonPop(this) {
                if (Build.VERSION.SDK_INT >= 33) {
                    requestPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        val intent = Intent()
                        intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                        intent.putExtra(Settings.EXTRA_APP_PACKAGE, this.packageName)
                        startActivity(intent)
                    }
                }

            }.show()
        }
    }

    private fun setPageIndicate(p: Int) {
        binding.ll1.isSelected = false
        binding.ll2.isSelected = false
        binding.tv1.typeface = Typeface.DEFAULT
        binding.tv2.typeface = Typeface.DEFAULT
        when (p) {
            0 -> {
                binding.ll1.isSelected = true
                binding.tv1.typeface = Typeface.DEFAULT_BOLD
            }

            1 -> {
                binding.ll2.isSelected = true
                binding.tv2.typeface = Typeface.DEFAULT_BOLD
            }
        }
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showExitDialog()
        }
        binding.ll1.setOnClickListener {
            //            BarUtils.setStatusBarColor(this, Color.parseColor("#F4F5F9"))
            binding.viewpager2.currentItem = 0
        }
        binding.ll2.setOnClickListener {
//            BarUtils.setStatusBarColor(this, Color.parseColor("#F4F5F9"))
            binding.viewpager2.currentItem = 1
        }

    }

    override fun onResume() {
        super.onResume()

        lifecycleScope.launch(Dispatchers.Main) {
            delay(1000)
            showRateStarPopDialog()
        }
    }
    private fun requestNotifPermisson(): Boolean {
        val mNotificationManager =
            this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return mNotificationManager.importance != NotificationManager.IMPORTANCE_NONE
        } else {
            return true
        }
    }

}