package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Fingerprint
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.platform.BiometricAuthPerformer
import com.tt.honeyDue.platform.BiometricResult
import com.tt.honeyDue.platform.rememberBiometricAuth
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

/**
 * P6 Stream T — Lock screen shown when the app requires re-authentication.
 *
 * Parity with iOS LAContext-based unlock:
 *  1. On mount, auto-triggers the biometric prompt (unless the device has
 *     no biometric hardware, in which case we bypass).
 *  2. Counts consecutive failures locally; after 3 failures the PIN
 *     fallback UI is surfaced. PIN check is currently a TODO placeholder
 *     wired to [TODO_FALLBACK_PIN] — follow up to read from encrypted
 *     secure storage.
 *  3. Honeycomb-themed background via [WarmGradientBackground] +
 *     [OrganicIconContainer] to match the rest of the design system.
 */
@Composable
fun BiometricLockScreen(
    onUnlocked: () -> Unit,
    biometricAuth: BiometricAuthPerformer = rememberBiometricAuth(),
) {
    val lockState = remember { BiometricLockState(onUnlock = onUnlocked) }

    var authError by remember { mutableStateOf<String?>(null) }
    var showFallback by remember { mutableStateOf(false) }
    var pinInput by remember { mutableStateOf("") }
    var pinError by remember { mutableStateOf<String?>(null) }

    val promptTitle = stringResource(Res.string.biometric_prompt_title)
    val promptSubtitle = stringResource(Res.string.biometric_prompt_subtitle)

    // Callback that maps platform result back onto the state machine.
    fun triggerPrompt() {
        biometricAuth.authenticate(
            title = promptTitle,
            subtitle = promptSubtitle,
        ) { result ->
            when (result) {
                is BiometricResult.Success -> lockState.onBiometricSuccess()
                is BiometricResult.Failed -> {
                    authError = result.message
                    if (lockState.onBiometricFailure()) {
                        showFallback = true
                    }
                }
                is BiometricResult.NotAvailable -> {
                    // NO_HARDWARE bypass — release the lock.
                    lockState.onBiometricSuccess()
                }
            }
        }
    }

    // Auto-trigger biometric prompt on first composition.
    LaunchedEffect(Unit) {
        val availability = if (biometricAuth.isBiometricAvailable()) {
            BiometricLockState.Availability.AVAILABLE
        } else {
            BiometricLockState.Availability.NO_HARDWARE
        }
        if (lockState.onAppear(availability)) {
            triggerPrompt()
        }
    }

    Surface(
        modifier = Modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        WarmGradientBackground {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .imePadding()
                    .padding(32.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                OrganicIconContainer(
                    icon = Icons.Default.Lock,
                    size = 96.dp,
                    iconSize = 56.dp
                )

                Spacer(modifier = Modifier.height(OrganicSpacing.xl))

                Text(
                    text = stringResource(Res.string.biometric_lock_title),
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center
                )

                Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                Text(
                    text = stringResource(Res.string.biometric_lock_description),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center
                )

                if (authError != null && !showFallback) {
                    Spacer(modifier = Modifier.height(OrganicSpacing.lg))
                    Text(
                        text = authError ?: "",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error,
                        textAlign = TextAlign.Center
                    )
                }

                Spacer(modifier = Modifier.height(OrganicSpacing.xl))

                if (showFallback) {
                    // ----- Fallback PIN UI (after 3 biometric failures) -----
                    Text(
                        text = "Enter PIN to unlock",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                        textAlign = TextAlign.Center
                    )
                    Spacer(modifier = Modifier.height(OrganicSpacing.md))
                    OutlinedTextField(
                        value = pinInput,
                        onValueChange = {
                            if (it.length <= 4 && it.all(Char::isDigit)) {
                                pinInput = it
                                pinError = null
                            }
                        },
                        label = { Text("4-digit PIN") },
                        singleLine = true,
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
                        isError = pinError != null,
                        supportingText = pinError?.let { { Text(it) } },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Spacer(modifier = Modifier.height(OrganicSpacing.md))
                    Button(
                        onClick = {
                            // TODO(P6-T follow-up): replace TODO_FALLBACK_PIN
                            // with a call to EncryptedSharedPreferences /
                            // iOS Keychain via TokenManager-style secure
                            // storage. See BiometricLockScreen.kt:line
                            // for the PIN constant below.
                            if (!lockState.onPinEntered(pinInput, TODO_FALLBACK_PIN)) {
                                pinError = "Incorrect PIN"
                            }
                        },
                        enabled = pinInput.length == 4,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(56.dp),
                        shape = MaterialTheme.shapes.medium,
                    ) {
                        Text(
                            text = "Unlock",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                } else {
                    // ----- Default biometric retry button -----
                    Button(
                        onClick = {
                            authError = null
                            if (lockState.onRetry()) {
                                triggerPrompt()
                            } else {
                                // 3-strike reached — flip to PIN fallback.
                                showFallback = true
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(56.dp),
                        shape = MaterialTheme.shapes.medium,
                    ) {
                        Icon(
                            imageVector = Icons.Default.Fingerprint,
                            contentDescription = null, // decorative
                            modifier = Modifier.size(24.dp)
                        )
                        Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                        Text(
                            text = stringResource(Res.string.biometric_unlock_button),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                }
            }
        }
    }
}

/**
 * TODO(P6-T follow-up): wire to secure storage.
 *
 * Currently a hard-coded placeholder so the fallback PIN entry path has
 * a concrete value to compare against. Before shipping, replace reads of
 * this constant with a lookup in EncryptedSharedPreferences (Android) /
 * Keychain (iOS) via the same pattern used by TokenManager.
 */
internal const val TODO_FALLBACK_PIN: String = "0000"
