package app.closer.ui.settings

import androidx.biometric.BiometricPrompt
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Fingerprint
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.data.local.RecoveryPhraseStore
import app.closer.domain.repository.SettingsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class SecurityUiState(
    val biometricLoginEnabled: Boolean = false,
    val hasRecoveryPhrase: Boolean = false,
    val recoveryPhrase: String? = null
)

@HiltViewModel
class SecurityViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
    private val recoveryPhraseStore: RecoveryPhraseStore
) : ViewModel() {

    private val _recoveryPhrase = MutableStateFlow<String?>(null)

    val uiState: StateFlow<SecurityUiState> = combine(
        settingsRepository.settings,
        _recoveryPhrase
    ) { settings, phrase ->
        SecurityUiState(
            biometricLoginEnabled = settings.biometricLoginEnabled,
            hasRecoveryPhrase = recoveryPhraseStore.load() != null,
            recoveryPhrase = phrase
        )
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SecurityUiState())

    fun setBiometricLogin(enabled: Boolean) {
        viewModelScope.launch { settingsRepository.setBiometricLogin(enabled) }
    }

    fun revealRecoveryPhrase() {
        _recoveryPhrase.update { recoveryPhraseStore.load() }
    }

    fun hideRecoveryPhrase() {
        _recoveryPhrase.update { null }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SecurityScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: SecurityViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()
    val context = LocalContext.current

    fun launchBiometricForPhrase() {
        val activity = context as? FragmentActivity ?: return
        BiometricPrompt(
            activity,
            ContextCompat.getMainExecutor(context),
            object : BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                    viewModel.revealRecoveryPhrase()
                }
            }
        ).authenticate(
            BiometricPrompt.PromptInfo.Builder()
                .setTitle("Recovery phrase")
                .setDescription("Authenticate to view your recovery phrase")
                .setAllowedAuthenticators(
                    androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG or
                            androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
                )
                .build()
        )
    }

    state.recoveryPhrase?.let { phrase ->
        AlertDialog(
            onDismissRequest = viewModel::hideRecoveryPhrase,
            title = { Text("Recovery phrase", color = SettingsInk) },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    Text(
                        "Write this down and keep it somewhere safe. You'll need it to restore your encrypted history if both devices are lost.",
                        style = MaterialTheme.typography.bodySmall,
                        color = SettingsMuted
                    )
                    Text(
                        phrase,
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.SemiBold,
                        color = SettingsInk
                    )
                }
            },
            confirmButton = {
                TextButton(onClick = viewModel::hideRecoveryPhrase) { Text("Done") }
            },
            containerColor = SettingsSoft
        )
    }

    SettingsSubpage(title = "Security", onBack = { onNavigate("back") }) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(padding)
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(containerColor = SettingsCard)
            ) {
                Column {
                    // Biometric login toggle
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp, vertical = 8.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Icon(Icons.Filled.Fingerprint, contentDescription = null, tint = SettingsMuted)
                        Text(
                            text = "Biometric login",
                            style = MaterialTheme.typography.bodyLarge,
                            color = SettingsInk,
                            modifier = Modifier.weight(1f)
                        )
                        Switch(
                            checked = state.biometricLoginEnabled,
                            onCheckedChange = { viewModel.setBiometricLogin(it) }
                        )
                    }

                    Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)

                    // Recovery phrase row — greyed out until a phrase is stored on-device
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .then(
                                if (state.hasRecoveryPhrase)
                                    Modifier.clickable { launchBiometricForPhrase() }
                                else Modifier
                            )
                            .padding(horizontal = 16.dp, vertical = 14.dp)
                            .alpha(if (state.hasRecoveryPhrase) 1f else 0.35f),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Icon(Icons.Filled.Lock, contentDescription = null, tint = SettingsMuted)
                        Text(
                            text = "Recovery phrase",
                            style = MaterialTheme.typography.bodyLarge,
                            color = SettingsInk,
                            modifier = Modifier.weight(1f)
                        )
                    }
                }
            }

            if (!state.hasRecoveryPhrase) {
                Text(
                    text = "Recovery phrase becomes available after you invite your partner.",
                    style = MaterialTheme.typography.bodySmall,
                    color = SettingsMuted,
                    modifier = Modifier.padding(horizontal = 4.dp)
                )
            }

            Spacer(Modifier.height(8.dp))
        }
    }
}
