package com.mobiuz.app.dev

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.mobiuz.app.databinding.ActivitySplashBinding
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.network.model.UiStateObject
import com.mobiuz.app.dev.ui.auth.AuthActivity
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.utils.extensions.showMessage
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import javax.inject.Inject


@AndroidEntryPoint
class SplashActivity : AppCompatActivity() {

    private var _bn: ActivitySplashBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val viewModel: MainViewModel by viewModels()
    @Inject
    lateinit var pref: SharedPref

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _bn = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(bn.root)

        viewModel.services()
        bn.btnTryAgain.setOnClickListener(object : ButtonClick(){
            override fun onSingleClick(v: View?) {
                viewModel.services()
            }
        })
        lifecycleScope.launchWhenStarted {
            viewModel.servicesUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        bn.btnTryAgain.isVisible = false
                        navigate()
                    }
                    is UiStateObject.ERROR -> {
                        bn.btnTryAgain.isVisible = true
                        showMessage(it.message)
                    }
                    is UiStateObject.LOADING -> {
                        bn.btnTryAgain.isVisible = false
                    }
                    else -> Unit
                }
            }
        }

    }

    fun navigate(){
        when {
            pref.language.isEmpty() -> {
                startActivity(Intent(this@SplashActivity, LanguageActivity::class.java))
            }

            !pref.isRegistered -> {
                startActivity(Intent(this@SplashActivity, AuthActivity::class.java))
            }

            pref.pinCode.isEmpty() -> {
                startActivity(Intent(this@SplashActivity, AuthActivity::class.java).putExtra(CONSTANTS.TYPE_AUTH, CONSTANTS.PIN_CODE))
            }

            else -> {
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            }
        }
        finish()
    }

    override fun onDestroy() {
        _bn = null
        super.onDestroy()
    }
}