package com.github.nullptroma.wallenc.app

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.github.nullptroma.wallenc.app.auth.YandexSignInService
import com.github.nullptroma.wallenc.ui.WallencUi
import com.github.nullptroma.wallenc.ui.navigation.matchesWallencDeepLink
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
import javax.inject.Inject


@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject
    lateinit var yandexSignInService: YandexSignInService

    private val deepLinkPulse = mutableIntStateOf(0)
    private var deepLinkIntentForNav: Intent by mutableStateOf(Intent())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        yandexSignInService.registerWith(this)
        enableEdgeToEdge()
        requestNotificationPermissionIfNeeded()

        Timber.plant(Timber.DebugTree())

        deepLinkIntentForNav = intent
        if (intent.matchesWallencDeepLink()) {
            deepLinkPulse.intValue++
        }

        setContent {
            val pulse by deepLinkPulse
            WallencUi(
                deepLinkPulse = pulse,
                deepLinkIntent = deepLinkIntentForNav,
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        deepLinkIntentForNav = intent
        if (intent.matchesWallencDeepLink()) {
            deepLinkPulse.intValue++
        }
    }

    override fun onDestroy() {
        yandexSignInService.unregister(this)
        super.onDestroy()
    }

    private fun requestNotificationPermissionIfNeeded() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
        val granted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.POST_NOTIFICATIONS,
        ) == PackageManager.PERMISSION_GRANTED
        if (granted) return
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.POST_NOTIFICATIONS),
            NOTIFICATION_PERMISSION_REQUEST_CODE,
        )
    }

    companion object {
        private const val NOTIFICATION_PERMISSION_REQUEST_CODE = 100
    }
}
