package com.rosetta.messenger.ui.auth

import androidx.activity.compose.BackHandler
import androidx.compose.animation.*
import androidx.compose.animation.core.tween
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import com.rosetta.messenger.data.DecryptedAccount
import com.rosetta.messenger.data.AccountManager
import com.rosetta.messenger.di.ProtocolGateway
import com.rosetta.messenger.di.SessionCoordinator

enum class AuthScreen {
    SELECT_ACCOUNT,
    WELCOME,
    SEED_PHRASE,
    CONFIRM_SEED,
    SET_PASSWORD,
    SET_BIOMETRIC,
    SET_PROFILE,
    IMPORT_SEED,
    UNLOCK
}

@Composable
fun AuthFlow(
    isDarkTheme: Boolean,
    hasExistingAccount: Boolean,
    accounts: List<AccountInfo> = emptyList(),
    accountManager: AccountManager,
    protocolGateway: ProtocolGateway,
    sessionCoordinator: SessionCoordinator,
    startInCreateMode: Boolean = false,
    onAuthComplete: (DecryptedAccount?) -> Unit,
    onLogout: () -> Unit = {}
) {
    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as? android.app.Activity)?.window ?: return@SideEffect
            val insetsController = WindowCompat.getInsetsController(window, view)
            window.statusBarColor = android.graphics.Color.TRANSPARENT
            // Auth flow should always use light (white) status bar icons.
            insetsController.isAppearanceLightStatusBars = false
        }
    }

    var currentScreen by remember { 
        mutableStateOf(
            when {
                startInCreateMode -> AuthScreen.WELCOME
                hasExistingAccount -> AuthScreen.UNLOCK
                else -> AuthScreen.WELCOME
            }
        ) 
    }
    var seedPhrase by remember { mutableStateOf<List<String>>(emptyList()) }
    var createdAccount by remember { mutableStateOf<DecryptedAccount?>(null) }
    // Use last logged account or fallback to first account
    var selectedAccountId by remember { 
        mutableStateOf<String?>(
            accountManager.getLastLoggedPublicKey() ?: accounts.firstOrNull()?.id
        ) 
    }
    var showCreateModal by remember { mutableStateOf(false) }
    var isImportMode by remember { mutableStateOf(false) }

    LaunchedEffect(currentScreen, selectedAccountId) {
        sessionCoordinator.markAuthInProgress(
            publicKey = selectedAccountId,
            reason = "auth_flow_${currentScreen.name.lowercase()}"
        )
    }

    // If parent requests create mode while AuthFlow is alive, jump to Welcome/Create path.
    LaunchedEffect(startInCreateMode) {
        if (startInCreateMode && currentScreen == AuthScreen.UNLOCK) {
            currentScreen = AuthScreen.WELCOME
        }
    }
    
    // Handle system back button
    BackHandler(enabled = currentScreen != AuthScreen.UNLOCK && !(currentScreen == AuthScreen.WELCOME && !hasExistingAccount)) {
        when (currentScreen) {
            AuthScreen.WELCOME -> {
                if (hasExistingAccount) currentScreen = AuthScreen.UNLOCK
            }
            AuthScreen.SEED_PHRASE -> {
                currentScreen = if (hasExistingAccount) AuthScreen.WELCOME else AuthScreen.WELCOME
            }
            AuthScreen.CONFIRM_SEED -> currentScreen = AuthScreen.SEED_PHRASE
            AuthScreen.SET_PASSWORD -> {
                if (isImportMode) {
                    currentScreen = AuthScreen.IMPORT_SEED
                } else if (hasExistingAccount) {
                    currentScreen = AuthScreen.UNLOCK
                } else {
                    currentScreen = AuthScreen.SEED_PHRASE
                }
            }
            AuthScreen.SET_BIOMETRIC -> {
                currentScreen = AuthScreen.SET_PROFILE
            }
            AuthScreen.SET_PROFILE -> {
                onAuthComplete(createdAccount)
            }
            AuthScreen.IMPORT_SEED -> {
                if (isImportMode && hasExistingAccount) {
                    currentScreen = AuthScreen.UNLOCK
                    isImportMode = false
                } else {
                    currentScreen = AuthScreen.WELCOME
                }
            }
            else -> {} // UNLOCK doesn't have back navigation
        }
    }
    
    AnimatedContent(
        targetState = currentScreen,
        transitionSpec = {
            fadeIn(animationSpec = tween(200)) togetherWith
            fadeOut(animationSpec = tween(200))
        },
        label = "authScreenTransition"
    ) { screen ->
        when (screen) {
            AuthScreen.SELECT_ACCOUNT -> {
                SelectAccountScreen(
                    isDarkTheme = isDarkTheme,
                    accounts = accounts,
                    selectedAccountId = selectedAccountId,
                    onSelectAccount = { accountId ->
                        selectedAccountId = accountId
                        currentScreen = AuthScreen.UNLOCK
                    },
                    onAddAccount = { showCreateModal = true },
                    showCreateModal = showCreateModal,
                    onCreateNew = {
                        showCreateModal = false
                        currentScreen = AuthScreen.SEED_PHRASE
                    },
                    onImportSeed = {
                        showCreateModal = false
                        currentScreen = AuthScreen.IMPORT_SEED
                    },
                    onDismissModal = { showCreateModal = false }
                )
            }
            
            AuthScreen.WELCOME -> {
                WelcomeScreen(
                    isDarkTheme = isDarkTheme,
                    hasExistingAccount = hasExistingAccount,
                    onBack = { currentScreen = AuthScreen.UNLOCK },
                    onCreateSeed = { currentScreen = AuthScreen.SEED_PHRASE },
                    onImportSeed = { currentScreen = AuthScreen.IMPORT_SEED }
                )
            }
            
            AuthScreen.SEED_PHRASE -> {
                SeedPhraseScreen(
                    isDarkTheme = isDarkTheme,
                    onBack = { currentScreen = AuthScreen.WELCOME },
                    onConfirm = { words ->
                        seedPhrase = words
                        currentScreen = AuthScreen.SET_PASSWORD
                    }
                )
            }

            AuthScreen.CONFIRM_SEED -> {
                // Skipped — go directly from SEED_PHRASE to SET_PASSWORD
                LaunchedEffect(Unit) { currentScreen = AuthScreen.SET_PASSWORD }
            }
            
            AuthScreen.SET_PASSWORD -> {
                SetPasswordScreen(
                    seedPhrase = seedPhrase,
                    isDarkTheme = isDarkTheme,
                    isImportMode = isImportMode,
                    accountManager = accountManager,
                    sessionCoordinator = sessionCoordinator,
                    onBack = {
                        if (isImportMode) {
                            currentScreen = AuthScreen.IMPORT_SEED
                        } else if (hasExistingAccount) {
                            currentScreen = AuthScreen.UNLOCK
                        } else {
                            currentScreen = AuthScreen.SEED_PHRASE
                        }
                    },
                    onAccountCreated = { account ->
                        if (isImportMode) {
                            onAuthComplete(account)
                        } else {
                            createdAccount = account
                            currentScreen = AuthScreen.SET_BIOMETRIC
                        }
                    }
                )
            }

            AuthScreen.SET_BIOMETRIC -> {
                SetBiometricScreen(
                    isDarkTheme = isDarkTheme,
                    account = createdAccount,
                    onContinue = { currentScreen = AuthScreen.SET_PROFILE }
                )
            }
            
            AuthScreen.SET_PROFILE -> {
                SetProfileScreen(
                    isDarkTheme = isDarkTheme,
                    account = createdAccount,
                    protocolGateway = protocolGateway,
                    accountManager = accountManager,
                    onComplete = { onAuthComplete(createdAccount) },
                    onSkip = { onAuthComplete(createdAccount) }
                )
            }

            AuthScreen.IMPORT_SEED -> {
                ImportSeedPhraseScreen(
                    isDarkTheme = isDarkTheme,
                    onBack = { 
                        if (isImportMode && hasExistingAccount) {
                            currentScreen = AuthScreen.UNLOCK
                            isImportMode = false
                        } else {
                            currentScreen = AuthScreen.WELCOME
                        }
                    },
                    onSeedPhraseImported = { words ->
                        seedPhrase = words
                        currentScreen = AuthScreen.SET_PASSWORD
                    }
                )
            }
            
            AuthScreen.UNLOCK -> {
                UnlockScreen(
                    isDarkTheme = isDarkTheme,
                    selectedAccountId = selectedAccountId,
                    accountManager = accountManager,
                    sessionCoordinator = sessionCoordinator,
                    onUnlocked = { account -> onAuthComplete(account) },
                    onSwitchAccount = {
                        // Navigate to create new account screen
                        // Don't reset selectedAccountId so last logged account is remembered
                        isImportMode = false
                        currentScreen = AuthScreen.WELCOME
                    },
                    onRecover = {
                        // Go directly to seed import (like Desktop's "recover your password")
                        isImportMode = true
                        currentScreen = AuthScreen.IMPORT_SEED
                    }
                )
            }
        }
    }
}
