package com.bassbooster.soundeffects.equalizer.view

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.res.ResourcesCompat
import androidx.viewpager.widget.ViewPager

import com.bassbooster.equalizer.R
import com.bassbooster.soundeffects.equalizer.data.model.Tutorial
import com.bassbooster.equalizer.databinding.ActivityTutorialSplashBinding
import com.bassbooster.equalizer.utils.DialogUtils
import com.bassbooster.soundeffects.equalizer.utils.AppUtils
import com.bassbooster.soundeffects.equalizer.utils.NotificationListener
import com.bassbooster.soundeffects.equalizer.view.activity.onboarding.OnBoardingPagerAdapter
import com.bassbooster.soundeffects.equalizer.utils.SharedPreferencesUtil
import com.bassbooster.soundeffects.equalizer.utils.Utils


class ActivityTutorialSplash : AppCompatActivity() {
    private lateinit var binding: ActivityTutorialSplashBinding
    private lateinit var sharedPreferencesUtil: SharedPreferencesUtil

    private val itemList = arrayListOf<Tutorial>()
    private var nativeAdsLoaded = arrayListOf<Boolean>()
    private var mLastClickTime: Long = 0
//    private var mFirebaseAnalytics: FirebaseAnalytics? = null
    private var positions = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTutorialSplashBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        sharedPreferencesUtil = SharedPreferencesUtil(this)
        // Khởi tạo Firebase Analytics
//        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        binding.mRlNext.visibility = View.GONE
        setUpViewPager()
        addEvent()
        AppUtils.hideNavigationBar(this)
    }

    override fun onResume() {
        super.onResume()
        AppUtils.hideNavigationBar(this)
    }

    override fun onPause() {
        super.onPause()
        Utils.hideAdsResume()
    }

    @SuppressLint("NewApi")
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            AppUtils.hideNavigationBar(this)
        }
    }

    @SuppressLint("NewApi")
    private fun addEvent() {

    }

    private fun setUpViewPager() {
        // Gửi sự kiện "Chọn ngôn ngữ English" lên Firebase Analytics
        val params = Bundle()
        params.putString("onboarding1", "User views màn Onboarding 1")
//        mFirebaseAnalytics!!.logEvent("onboarding_1_view", params)

        val adapter = OnBoardingPagerAdapter(supportFragmentManager)
        binding.onboardingViewPager.addOnPageChangeListener(object :
            ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                if (positions>position){
                    // Gửi sự kiện "Chọn ngôn ngữ English" lên Firebase Analytics
                    val paramSwipeBack = Bundle()
                    paramSwipeBack.putString("swipeback", "User vuốt quay lại màn Onboarding ${positions+1}")
//                    mFirebaseAnalytics!!.logEvent("onboarding_${positions+1}_swipe_back", paramSwipeBack)
                }
                positions=position

                binding.btnNext.text =
                    if (position == 2 && positionOffset == 0f) resources.getString(R.string.get_start) else resources.getString(R.string.next)
            }

            override fun onPageSelected(position: Int) {
                prepareDot(position, arrayListOf(0,1,2))

                Log.d("qqq", "onPageSelected: ")
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
        prepareDot(0, arrayListOf(0,1,2))
        binding.onboardingViewPager.adapter = adapter

        binding.btnNext.setOnClickListener {
            if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
                return@setOnClickListener
            }
            mLastClickTime = SystemClock.elapsedRealtime()
            if (binding.onboardingViewPager.currentItem < adapter.count - 1) {
                // Chuyển đến Fragment tiếp theo
                binding.onboardingViewPager.currentItem = binding.onboardingViewPager.currentItem + 1

                // Gửi sự kiện "Chọn ngôn ngữ English" lên Firebase Analytics
                val params = Bundle()
                params.putString("onboarding_next", "User clicks next ở màn Onboarding ${binding.onboardingViewPager.currentItem}")
//                mFirebaseAnalytics!!.logEvent("onboarding_${binding.onboardingViewPager.currentItem}_next_click", params)

                // Gửi sự kiện "Chọn ngôn ngữ English" lên Firebase Analytics
                val paramView = Bundle()
                paramView.putString("onboarding_view", "User views màn Onboarding ${binding.onboardingViewPager.currentItem+1}")
//                mFirebaseAnalytics!!.logEvent("onboarding_${binding.onboardingViewPager.currentItem+1}_view", paramView)

                binding.btnNext.text = resources.getString(R.string.next)
            } else {
                // Ví dụ: chuyển đến màn hình chính của ứng dụng
                val params = Bundle()
                params.putString("onboarding_get_start", "User clicks get start ở màn Onboarding  ${binding.onboardingViewPager.currentItem+1}")
//                mFirebaseAnalytics!!.logEvent("onboarding_${binding.onboardingViewPager.currentItem+1}_get_start_click", params)

                sharedPreferencesUtil.isFirstSplash("isFirstSplash", true)
                openHome()
            }
        }
    }

    private fun prepareDot(dotPosition: Int, listBanner: List<Int>) {
        if (binding.dotsSlide.childCount > 0) {
            binding.dotsSlide.removeAllViews()
        }

        for (i in listBanner.indices) {
            val dot = ImageView(this)
            if (i == dotPosition) {
                dot.setImageDrawable(
                    ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.indicator_main_unselected,
                        null
                    )
                )
            } else {
                dot.setImageDrawable(
                    ResourcesCompat.getDrawable(
                        resources,
                        R.drawable.indicator_main_selected,
                        null
                    )
                )
            }

            val layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.marginStart = 20
            binding.dotsSlide.addView(dot, layoutParams)
        }
    }

    private fun checkAudioPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun checkModifyAudioPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.MODIFY_AUDIO_SETTINGS
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestAudioPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.RECORD_AUDIO),
            28
        )
    }

    private fun requestModifyAudioPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.MODIFY_AUDIO_SETTINGS),
            27
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 28) { // Sử dụng requestCode bạn đã chọn ở bước 1
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkPermissionNotification()
            } else {
                DialogUtils.showDialog(this,
                    resources.getString(R.string.notification_content_visua),
                    listenerOK = {

                        val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", packageName, null)
                        intent.data = uri
                        startActivityForResult(intent,28)
                    })
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 28){
            if (checkAudioPermission()) {
                checkPermissionNotification()
            } else {
                DialogUtils.showDialog(this,
                    resources.getString(R.string.notification_content_visua),
                    listenerOK = {


                        val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", packageName, null)
                        intent.data = uri
                        startActivityForResult(intent,28)
                    })
            }
        }else{
            openHome()
        }
    }

    private fun checkPermissionNotification(){
        if (checkModifyAudioPermission()) {
            if (!NotificationListener.isEnabled(this)) {
                DialogUtils.showDialogConfirmPer(this,
                    "Notification",
                    resources.getString(R.string.notification_content),
                    listenerOK = {

                        startActivityForResult(
                            Intent(
                                "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"
                            ), 100
                        )
//                                sharedPreferencesUtil.saveBoolean("NOTIFICATION_LISTENER_SETTINGS",true)
                    },
                    listenerCancel = {
                        openHome()
                    })
            }else{
                openHome()
            }
        } else {
            requestModifyAudioPermission()
        }
    }

    private fun openHome(){
        val intent = Intent(
            this@ActivityTutorialSplash, MainActivity::class.java
        )
        startActivity(intent)
        finish()
    }

    override fun onBackPressed() {
        finishAffinity()
    }
}
