package app.closer

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import app.closer.BuildConfig
import app.closer.core.navigation.AppNavigation
import app.closer.domain.repository.AppSettings
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.SettingsRepository
import app.closer.domain.repository.ThemeMode
import app.closer.ui.theme.CloserTheme
import com.google.firebase.auth.FirebaseAuth
import dagger.hilt.android.AndroidEntryPoint
import java.io.File
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject lateinit var settingsRepository: SettingsRepository
    @Inject lateinit var authRepository: AuthRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (BuildConfig.DEBUG) attemptDebugAutoLogin()
        setContent {
            val settings by settingsRepository.settings.collectAsState(initial = AppSettings())
            val systemInDarkTheme = isSystemInDarkTheme()
            val useDarkTheme = when (settings.themeMode) {
                ThemeMode.DEVICE -> systemInDarkTheme
                ThemeMode.LIGHT -> false
                ThemeMode.DARK -> true
            }

            var sessionVerified by remember { mutableStateOf(false) }
            val needsBiometricLock = settings.biometricLoginEnabled
                && authRepository.currentUserId != null
                && !sessionVerified

            CloserTheme(darkTheme = useDarkTheme) {
                SideEffect {
                    WindowCompat.getInsetsController(window, window.decorView).apply {
                        isAppearanceLightStatusBars = !useDarkTheme
                        isAppearanceLightNavigationBars = !useDarkTheme
                    }
                }
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    if (needsBiometricLock) {
                        BiometricLockScreen(
                            activity = this@MainActivity,
                            onUnlocked = { sessionVerified = true }
                        )
                    } else {
                        AppNavigation()
                    }
                }
            }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
    }

    private fun attemptDebugAutoLogin() {
        val tokenFile = File(filesDir, "closer_debug_token.txt")
        if (!tokenFile.exists()) return
        val token = tokenFile.readText().trim()
        tokenFile.delete()
        if (token.isBlank()) return
        Log.d("CloserDebug", "Signing in with debug custom token")
        FirebaseAuth.getInstance().signInWithCustomToken(token)
            .addOnSuccessListener { Log.d("CloserDebug", "Debug sign-in succeeded") }
            .addOnFailureListener { e -> Log.e("CloserDebug", "Debug sign-in failed", e) }
    }
}

@Composable
private fun BiometricLockScreen(activity: AppCompatActivity, onUnlocked: () -> Unit) {
    LaunchedEffect(Unit) {
        BiometricPrompt(
            activity,
            ContextCompat.getMainExecutor(activity),
            object : BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                    onUnlocked()
                }
            }
        ).authenticate(
            BiometricPrompt.PromptInfo.Builder()
                .setTitle("Unlock Closer")
                .setSubtitle("Verify it's you to continue")
                .setAllowedAuthenticators(
                    BiometricManager.Authenticators.BIOMETRIC_STRONG or
                            BiometricManager.Authenticators.DEVICE_CREDENTIAL
                )
                .build()
        )
    }
    Box(modifier = Modifier.fillMaxSize())
}
