package com.bassbooster.soundeffects.equalizer.view.activity

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.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.bassbooster.equalizer.R
import com.bassbooster.equalizer.databinding.ActivitySplashBinding
import com.bassbooster.equalizer.utils.DialogUtils
import com.bassbooster.soundeffects.equalizer.utils.SharedPreferencesUtil
import com.bassbooster.soundeffects.equalizer.view.MainActivity
import com.bassbooster.soundeffects.equalizer.utils.AppUtils
import com.bassbooster.soundeffects.equalizer.utils.NotificationListener
import com.bassbooster.soundeffects.equalizer.view.activity.setting.language.LanguageActivity
import com.bassbooster.soundeffects.equalizer.view.activity.setting.language.LanguageManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers


class SplashActivity : AppCompatActivity() {
    private lateinit var binding: ActivitySplashBinding
    private lateinit var sharedPreferencesUtil: SharedPreferencesUtil
    private val languageManager = LanguageManager()
    private var isFirstRunApp = true
    private var isAppOnBackground = false
    val scope = CoroutineScope(Dispatchers.IO) // Sử dụng luồng nền
//    private var mFirebaseAnalytics: FirebaseAnalytics? = null

    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharedPreferencesUtil = SharedPreferencesUtil(this)
        languageManager.languageManager(this@SplashActivity)
        binding = ActivitySplashBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        // Khởi tạo Firebase Analytics
//        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this)
        init()
    }

    private fun init() {
        AppUtils.hideNavigationBar(this)

        // Sử dụng coroutine để thực hiện công việc bất đồng bộ
        startMain(true)
    }

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

//    var adCallback: AperoAdCallback = object : AperoAdCallback() {
//        override fun onAdClicked() {
//            super.onAdClicked()
//            tracKingFirebaseAnalytics(mFirebaseAnalytics,"Inter_splash_click","click ad","splash_click")
//
//        }
//        override fun onAdFailedToLoad(i: ApAdError?) {
//            super.onAdFailedToLoad(i)
//            Log.d("TAG", "onAdLoaded")
//        }
//
//        override fun onAdLoaded() {
//            super.onAdLoaded()
//            Log.d("TAG", "onAdLoaded")
//        }
//
//        override fun onNextAction() {
//            super.onNextAction()
//            Log.d("TAG", "onNextAction")
////            startMain(false)
//        }
//
//        override fun onAdClosed() {
//            super.onAdClosed()
//            startMain(false)
//            Log.d("TAG", "onAdClosed")
//        }
//    }
//
//    private fun loadSplash() {
//        tracKingFirebaseAnalytics(mFirebaseAnalytics,"Inter_splash_view","view ad tại màn Splash","splash_view")
//
//        Log.d("TAG", "onCreate: show splash ads")
//        //        AperoAd.getInstance().setInitCallback(() ->
////                AperoAd.getInstance().loadSplashInterstitialAds(SplashActivity.this,
////                        BuildConfig.inter_splash, 30000, 3000, false, adCallback)
////        );
////        AppOpenManager.getInstance().setSplashAdId(BuildConfig.inter_splash);
//        AperoAd.getInstance().setInitCallback {
//            AperoAd.getInstance().loadSplashInterstitialAds(
//                this,
//                BuildConfig.Inter_splash,
//                30000,
//                2000,
//                true,
//                adCallback
//            )
//        }
//
//    }

    private fun startMain(delay: Boolean) {
        sharedPreferencesUtil = SharedPreferencesUtil(this)
        languageManager.updateResource(sharedPreferencesUtil.getString("lang"))
        if (!sharedPreferencesUtil.getIsFirstSplash("isFirstSplash")) {
            val intent = Intent(this@SplashActivity, LanguageActivity::class.java)
            startActivity(intent)
            finish()
        } else {
            val intent = Intent(this@SplashActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        AppUtils.hideNavigationBar(this)
        Log.e("TAG", "Splash onPause: ")
        if (isFirstRunApp) {
            isFirstRunApp = false
            return
        }

    }


    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 {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

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

                        startActivityForResult(
                            Intent(
                                "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"
                            ), 100
                        )
//                                sharedPreferencesUtil.saveBoolean("NOTIFICATION_LISTENER_SETTINGS",true)
                    },
                    listenerCancel = {
                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                        finish()
                    })
            } else {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        } else {
            requestModifyAudioPermission()
        }
    }

    override fun onStart() {
        super.onStart()
        isAppOnBackground = false
    }


}