package com.prodhack.moscow2025.presentation

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import com.google.firebase.messaging.FirebaseMessaging
import com.prodhack.moscow2025.domain.usecase.auth.CheckSessionUseCase
import com.prodhack.moscow2025.domain.usecase.auth.SendFCMTokenUseCase
import com.prodhack.moscow2025.domain.usecase.auth.SessionState
import com.prodhack.moscow2025.presentation.navigation.AppDestination
import com.prodhack.moscow2025.presentation.navigation.TTasksApp
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.koin.android.ext.android.inject
import kotlin.getValue

class MainActivity : ComponentActivity() {

	private companion object {
		const val TAG = "MainActivity"
	}

	private val checkSessionUseCase: CheckSessionUseCase by inject()

	private val sendFCMTokenUseCase: SendFCMTokenUseCase by inject()
	private val sessionDestinationState = MutableStateFlow<AppDestination?>(null)

	override fun onCreate(savedInstanceState: Bundle?) {
		val splashScreen = installSplashScreen()
		var stateLoaded = false
		splashScreen.setKeepOnScreenCondition {
			stateLoaded.not()
		}
		super.onCreate(savedInstanceState)
		enableEdgeToEdge()
		WindowCompat.setDecorFitsSystemWindows(window, false)

		runBlocking {
			val sessionState = try {
				checkSessionUseCase().also {
					Log.d(TAG, "SessionState received $it")
				}
			} catch (e: Exception) {
				Log.e(TAG, "Exception in session state getting process", e)
				SessionState.NotAuthorized
			}
			sessionDestinationState.value =
				when (sessionState) {
					SessionState.NotAuthorized -> AppDestination.Login
					SessionState.NotFilledProfile -> AppDestination.FillProfile
					SessionState.FilledAndAuthorized -> AppDestination.Main
				}

			stateLoaded = true
		}

		setContent {
			val sessionDestination by sessionDestinationState.collectAsState()
			TTasksApp(
				sessionDestination = sessionDestination,
				context = this,
				requestNotifyPermissions = {
					checkAndRequestNotificationPermission()
				}
			)
		}
	}

	private fun checkAndRequestNotificationPermission() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
			when {
				ContextCompat.checkSelfPermission(
					this,
					Manifest.permission.POST_NOTIFICATIONS
				) == PackageManager.PERMISSION_GRANTED -> {
					getFCMToken()
				}

				else -> {
					requestPermissions(
						arrayOf(Manifest.permission.POST_NOTIFICATIONS),
						123
					)
				}
			}
		} else {
			getFCMToken()
		}
	}

	fun getFCMToken() {
		FirebaseMessaging.getInstance().token
			.addOnCompleteListener { task ->
				if (task.isSuccessful) {
					val token = task.result
					Log.d("TOKEN", token)
					lifecycleScope.launch {
						sendFCMTokenUseCase(token)
					}
				} else {
					Log.e("TOKEN", "Failed to get token", task.exception)
				}
			}
	}

	override fun onRequestPermissionsResult(
		requestCode: Int,
		permissions: Array<String>,
		grantResults: IntArray,
		deviceId: Int
	) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults)
		if (requestCode == 123) {
			if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				getFCMToken()
			}
		}
	}

}