package kr.co.vividnext.sodalive.onboarding

import android.content.Intent
import com.google.android.material.tabs.TabLayoutMediator
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ActivityOnboardingBinding
import kr.co.vividnext.sodalive.main.MainActivity
import kr.co.vividnext.sodalive.user.login.LoginActivity

class OnBoardingActivity : BaseActivity<ActivityOnboardingBinding>(
    ActivityOnboardingBinding::inflate
) {

    private lateinit var adapter: OnBoardingViewPagerAdapter

    override fun setupView() {
        setupViewPager()
        setupTabLayout()
        setupButtonEvent()
    }

    private fun setupViewPager() {
        binding.viewPager.offscreenPageLimit = 9

        adapter = OnBoardingViewPagerAdapter(this)
        adapter.addFragment(OnBoardingFragment(R.drawable.img_guide_0))
        adapter.addFragment(OnBoardingFragment(R.drawable.img_guide_1))
        adapter.addFragment(OnBoardingFragment(R.drawable.img_guide_2))
        adapter.addFragment(OnBoardingFragment(R.drawable.img_guide_3))
        adapter.addFragment(OnBoardingFragment(R.drawable.img_guide_4))
        binding.viewPager.adapter = adapter
    }

    private fun setupTabLayout() {
        TabLayoutMediator(binding.tabs, binding.viewPager) { _, _ -> }.attach()
    }

    private fun setupButtonEvent() {
        binding.tvStart.setOnClickListener { moveNextActivity() }
    }

    private fun moveNextActivity() {
        SharedPreferenceManager.isViewedOnboardingTutorial = true

        if (SharedPreferenceManager.token.isBlank()) {
            val nextIntent = Intent(applicationContext, LoginActivity::class.java)
            val extras = intent.getBundleExtra(Constants.EXTRA_DATA)
                ?: if (intent.extras != null) {
                    intent.extras
                } else {
                    null
                }
            if (extras != null) {
                nextIntent.putExtra(Constants.EXTRA_DATA, extras)
            }
            startActivity(nextIntent)
        } else {
            val nextIntent = Intent(applicationContext, MainActivity::class.java)
            val extras = intent.getBundleExtra(Constants.EXTRA_DATA)
                ?: if (intent.extras != null) {
                    intent.extras
                } else {
                    null
                }
            if (extras != null) {
                nextIntent.putExtra(Constants.EXTRA_DATA, extras)
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            startActivity(nextIntent)
        }

        finish()
    }
}
