package kr.co.vividnext.sodalive.splash

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import com.google.firebase.dynamiclinks.PendingDynamicLinkData
import com.google.firebase.dynamiclinks.ktx.dynamicLinks
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.get
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings
import kr.co.vividnext.sodalive.BuildConfig
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.base.SodaDialog
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ActivitySplashBinding
import kr.co.vividnext.sodalive.main.MainActivity
import kr.co.vividnext.sodalive.onboarding.OnBoardingActivity
import kr.co.vividnext.sodalive.user.login.LoginActivity

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity<ActivitySplashBinding>(ActivitySplashBinding::inflate) {

    private val handler = Handler(Looper.getMainLooper())
    private val remoteConfig = Firebase.remoteConfig

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setLayoutParams(binding.ivText, start = 0, end = 0, top = 300, bottom = 0)
        setLayoutParams(binding.ivText2, start = 0, end = 0, top = 0, bottom = 180)

        setupRemoteConfig()
        fetchAndroidLatestVersion()
    }

    private fun setLayoutParams(
        imageView: ImageView,
        start: Int = 0,
        end: Int = 0,
        top: Int = 0,
        bottom: Int = 0
    ) {
        val lp = imageView.layoutParams as ConstraintLayout.LayoutParams

        if (top > 0) {
            lp.topMargin = screenHeight * top / 2337
        }

        if (bottom > 0) {
            lp.bottomMargin = screenHeight * bottom / 2337
        }

        if (start > 0) {
            lp.leftMargin = screenWidth * start / 1080
        }

        if (end > 0) {
            lp.rightMargin = screenWidth * end / 1080
        }

        imageView.layoutParams = lp
    }

    private fun setupRemoteConfig() {
        val configSettings = remoteConfigSettings {
            minimumFetchIntervalInSeconds = 60
        }
        remoteConfig.setConfigSettingsAsync(configSettings)
    }

    private fun fetchAndroidLatestVersion() {
        remoteConfig.fetchAndActivate()
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    handler.post {
                        val isMaintenance = remoteConfig["is_maintenance"].asBoolean()
                        if (isMaintenance) {
                            SodaDialog(
                                activity = this@SplashActivity,
                                layoutInflater = layoutInflater,
                                title = "안내",
                                desc = "서비스 점검중입니다.",
                                confirmButtonTitle = "확인",
                                confirmButtonClick = { finish() }
                            ).show(screenWidth)
                        } else {
                            checkAppVersion(remoteConfig["android_latest_version"].asString())
                        }
                    }
                } else {
                    checkFirebaseDynamicLink()
                }
            }
    }

    private fun checkAppVersion(latestVersion: String) {
        val versions = BuildConfig.VERSION_NAME.split(".")
        val latestVersions = latestVersion.split(".")

        if (latestVersions.isNotEmpty() && latestVersions.size == versions.size) {
            val latestMajor = latestVersions[0].toInt()
            val latestMinor = latestVersions[1].toInt()
            val latestPatch = latestVersions[2].toInt()

            val major = versions[0].toInt()
            val minor = versions[1].toInt()
            val patch = versions[2].toInt()

            if (latestMajor > major || (latestMajor == major && latestMinor > minor)) {
                showUpdateDialog(isEssential = true)
            } else if (latestMajor == major && latestMinor == minor && latestPatch > patch) {
                showUpdateDialog(isEssential = false)
            } else {
                checkFirebaseDynamicLink()
            }
        } else {
            checkFirebaseDynamicLink()
        }
    }

    private fun showUpdateDialog(isEssential: Boolean = false) {
        val desc = if (isEssential) {
            "필수 업데이트가 있습니다.\n업데이트 후 사용가능합니다."
        } else {
            "최신 업데이트가 있습니다.\n업데이트 하시겠습니까?"
        }

        val cancelButtonClick = if (!isEssential) {
            { checkFirebaseDynamicLink() }
        } else {
            null
        }

        SodaDialog(
            activity = this,
            layoutInflater = layoutInflater,
            title = "업데이트",
            desc = desc,
            confirmButtonTitle = "업데이트",
            confirmButtonClick = {
                startActivity(
                    Intent(
                        Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=${BuildConfig.APPLICATION_ID}")
                    )
                )
                finish()
            },
            cancelButtonTitle = if (isEssential) {
                ""
            } else {
                "다음에"
            },
            cancelButtonClick = cancelButtonClick
        ).show(screenWidth)
    }

    private fun checkFirebaseDynamicLink() {
        Firebase.dynamicLinks
            .getDynamicLink(intent)
            .addOnSuccessListener(this) { getDynamicLinkSuccess(it) }
            .addOnFailureListener(this) { getDynamicLinkFailure() }
    }

    private fun getDynamicLinkSuccess(pendingDynamicLinkData: PendingDynamicLinkData?) {
        var deepLink: Uri? = null
        if (pendingDynamicLinkData != null) {
            deepLink = pendingDynamicLinkData.link
        }

        val extras = if (deepLink != null) {
            val roomIdString = deepLink.getQueryParameter("room_id")
            val channelIdString = deepLink.getQueryParameter("channel_id")
            val audioContentIdString = deepLink.getQueryParameter("audio_content_id")

            if (roomIdString != null) {
                bundleOf(
                    Constants.EXTRA_ROOM_ID to roomIdString.toLong()
                )
            } else if (channelIdString != null) {
                bundleOf(
                    Constants.EXTRA_USER_ID to channelIdString.toLong()
                )
            } else if (audioContentIdString != null) {
                bundleOf(
                    Constants.EXTRA_AUDIO_CONTENT_ID to audioContentIdString.toLong()
                )
            } else {
                null
            }
        } else if (intent.extras != null) {
            intent.extras
        } else {
            null
        }

        startNextActivity(extras = extras)
    }

    private fun getDynamicLinkFailure() {
        val extras = intent.getBundleExtra(Constants.EXTRA_DATA)
            ?: if (intent.extras != null) {
                intent.extras
            } else {
                null
            }

        startNextActivity(extras = extras)
    }

    private fun startNextActivity(extras: Bundle? = null) {
        if (SharedPreferenceManager.isViewedOnboardingTutorial) {
            if (SharedPreferenceManager.token.isBlank()) {
                showLoginActivity(extras)
            } else {
                showMainActivity(extras)
            }
        } else {
            showOnBoardingTutorialActivity(extras)
        }
    }

    private fun showOnBoardingTutorialActivity(extras: Bundle?) {
        handler.postDelayed({
            startActivity(
                Intent(applicationContext, OnBoardingActivity::class.java).apply {
                    putExtra(Constants.EXTRA_DATA, extras)
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                }
            )
            finish()
        }, 1000)
    }

    private fun showMainActivity(extras: Bundle?) {
        handler.postDelayed({
            startActivity(
                Intent(applicationContext, MainActivity::class.java).apply {
                    putExtra(Constants.EXTRA_DATA, extras)
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                }
            )
            finish()
        }, 1000)
    }

    private fun showLoginActivity(extras: Bundle?) {
        handler.postDelayed({
            startActivity(
                Intent(applicationContext, LoginActivity::class.java).apply {
                    putExtra(Constants.EXTRA_DATA, extras)
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                }
            )
            finish()
        }, 1000)
    }

    override fun setupView() {}
}
