package com.cottondb.android.ui.passwords import androidx.compose.foundation.background 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.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.SecretKind import com.cottondb.android.generated.SecretPayload import com.cottondb.android.generated.CottonPalette import com.cottondb.android.passwords.PasswordFacts import com.cottondb.android.passwords.PasswordPlacement import com.cottondb.android.passwords.PasswordSecret import com.cottondb.android.passwords.PasswordSecretRead import com.cottondb.android.passwords.SecretDetailState import com.cottondb.android.passwords.SecretValueState import java.time.Clock import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale import kotlinx.serialization.json.JsonPrimitive /** * Metadata-only password detail page. Authenticated values arrive in [values] and never enter * remembered or saveable UI state. The owner supplies every operation, including vault locking. */ @Composable fun SecretDetailScreen( state: SecretDetailState, values: SecretValueState, clock: Clock, zoneId: ZoneId, onBack: () -> Unit, onReveal: () -> Unit, onHide: () -> Unit, onCopy: (fieldKey: String) -> Unit, onEdit: () -> Unit, onTrash: () -> Unit, onRestore: () -> Unit, onRetry: () -> Unit, onProject: (slug: String) -> Unit, onLock: () -> Unit, modifier: Modifier = Modifier, ) { var pendingAction by remember { mutableStateOf(null) } val read = state.detailRead() val error = (state as? SecretDetailState.Error)?.message ?: values.problem val loading = state == SecretDetailState.Loading val working = values.working || (state as? SecretDetailState.Data)?.working == true Column( modifier .fillMaxSize() .background(CottonPalette.groundMuted) .safeDrawingPadding() .verticalScroll(rememberScrollState()) .padding(horizontal = CottonMetrics.contentMargin), ) { Row( Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { TextButton(onClick = onBack, modifier = Modifier.testTag("secret-back")) { Text("Back") } Spacer(Modifier.weight(1f)) if (read?.secret != null) { TextButton(onClick = onLock, modifier = Modifier.testTag("secret-lock")) { Text("Lock") } } } when { loading -> SecretLoading() state is SecretDetailState.Error && read == null -> SecretFailed() read?.secret == null -> SecretMissing() else -> SecretCard( read = read, values = values, clock = clock, zoneId = zoneId, working = working, onReveal = onReveal, onHide = onHide, onCopy = onCopy, onEdit = onEdit, onTrashAsked = { pendingAction = SecretDetailAction.Trash }, onRestoreAsked = { pendingAction = SecretDetailAction.Restore }, onProject = onProject, ) } if (values.copied) { Text("Copied. Clear the clipboard when you’re done.", Modifier.testTag("secret-copied"), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } if (error != null) { Row( Modifier.fillMaxWidth().padding(vertical = 12.dp).testTag("secret-error"), verticalAlignment = Alignment.CenterVertically, ) { Text(error, Modifier.weight(1f), color = CottonPalette.statusError, style = CottonTextStyles.caption) TextButton(onClick = onRetry, modifier = Modifier.testTag("secret-retry")) { Text("Retry") } } } } pendingAction?.let { action -> val restoring = action == SecretDetailAction.Restore AlertDialog( onDismissRequest = { pendingAction = null }, title = { Text(if (restoring) "Put this back?" else "Move to bin?") }, text = { Text(if (restoring) "It will return to your passwords." else "You can restore it from the bin.") }, confirmButton = { TextButton( onClick = { pendingAction = null if (restoring) onRestore() else onTrash() }, enabled = !working, modifier = Modifier.testTag(if (restoring) "secret-confirm-restore" else "secret-confirm-trash"), ) { Text(if (restoring) "Put back" else "Move to bin") } }, dismissButton = { TextButton(onClick = { pendingAction = null }) { Text("Cancel") } }, ) } } @Composable private fun SecretCard( read: PasswordSecretRead, values: SecretValueState, clock: Clock, zoneId: ZoneId, working: Boolean, onReveal: () -> Unit, onHide: () -> Unit, onCopy: (String) -> Unit, onEdit: () -> Unit, onTrashAsked: () -> Unit, onRestoreAsked: () -> Unit, onProject: (String) -> Unit, ) { val secret = requireNotNull(read.secret) val kind = SecretKind.fromWire(secret.kind) val fields = secretFields(kind, values.payload) val lockedNote = PasswordFacts.lockedNote( isSet = secret.isSet, isLegacy = secret.legacy, hasKey = read.status?.hasKey == true, wrapped = read.status?.wrapped == true, ) val isOpen = values.payload != null val canReveal = secret.isSet && !secret.legacy && read.status?.wrapped == true Column( Modifier.fillMaxWidth().testTag("secret-detail"), verticalArrangement = Arrangement.spacedBy(10.dp), ) { Column( Modifier.fillMaxWidth().background(CottonPalette.groundElevated).padding(24.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text(secret.name, style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display)) Text( if (secret.trashedAt == null) PasswordFacts.kindWord(kind) else "${PasswordFacts.kindWord(kind)} · in the bin", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary, ) read.status?.let { status -> PasswordFacts.statusLine(status.hasKey, status.wrapped, status.legacyCount)?.let { line -> Text(line, Modifier.testTag("secret-status"), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } metadataRows(secret, zoneId).forEach { (label, value) -> DetailLine(label, value) } fields.forEach { field -> HorizontalDivider() SecretFieldLine( field = field, isOpen = isOpen, lockedNote = lockedNote, canReveal = canReveal, working = working, hint = secret.hint, onReveal = onReveal, onHide = onHide, onCopy = onCopy, ) } updatedLine(secret.updatedAt, clock, zoneId)?.let { updated -> Text(updated, Modifier.fillMaxWidth(), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } if (secret.trashedAt == null) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { TextButton(onClick = onEdit, enabled = !working, modifier = Modifier.testTag("secret-edit")) { Text("Edit") } TextButton(onClick = onTrashAsked, enabled = !working, modifier = Modifier.testTag("secret-trash")) { Text("Move to bin") } } } else { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { TextButton(onClick = onRestoreAsked, enabled = !working, modifier = Modifier.testTag("secret-restore")) { Text("Put back") } } } read.projects.forEach { project -> TextButton( onClick = { onProject(project.slug) }, modifier = Modifier.fillMaxWidth().testTag("secret-project-${project.slug}"), ) { Text(project.name, Modifier.fillMaxWidth()) } } read.placements.forEach { placement -> PlacementLine(placement, zoneId) } } } @Composable private fun SecretFieldLine( field: VisibleSecretField, isOpen: Boolean, lockedNote: String?, canReveal: Boolean, working: Boolean, hint: String?, onReveal: () -> Unit, onHide: () -> Unit, onCopy: (String) -> Unit, ) { val displayed = when { field.value != null -> field.value field.field.isSealed -> maskedSecret(if (field.field.isPrimary) hint else null) else -> "—" } Column(Modifier.fillMaxWidth().testTag("secret-field-${field.field.key}")) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(field.field.label, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) Text(displayed, maxLines = if (field.field.isMultiline) Int.MAX_VALUE else 1, overflow = TextOverflow.Ellipsis, style = CottonTextStyles.body) } if (field.field.isSealed && canReveal) { if (field.field.isPrimary) { TextButton( onClick = if (isOpen) onHide else onReveal, enabled = !working, modifier = Modifier.testTag("secret-reveal"), ) { Text(if (isOpen) "Hide" else "Reveal") } } TextButton( onClick = { onCopy(field.field.key) }, enabled = !working, modifier = Modifier.testTag("secret-copy-${field.field.key}"), ) { Text("Copy") } } } if (field.field.isPrimary && !canReveal) { lockedNote?.let { Text(it, Modifier.testTag("secret-locked"), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } } } @Composable private fun DetailLine(label: String, value: String) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text(label, Modifier.width(96.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) Text(value, Modifier.weight(1f), style = CottonTextStyles.body) } } @Composable private fun PlacementLine(placement: PasswordPlacement, zoneId: ZoneId) { Column(Modifier.fillMaxWidth().testTag("secret-placement-${placement.id}").padding(vertical = 4.dp)) { Text(placement.path, style = CottonTextStyles.body) placementStatus(placement, zoneId)?.let { Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary) } } } @Composable private fun SecretLoading() { Text("Loading password…", Modifier.testTag("secret-loading"), style = CottonTextStyles.body) } @Composable private fun SecretMissing() { Text("This one is gone.", Modifier.testTag("secret-missing"), style = CottonTextStyles.pageTitle) Text("It is not in this database any more.", style = CottonTextStyles.body, color = CottonPalette.inkSecondary) } @Composable private fun SecretFailed() { Text("This password could not be read.", Modifier.testTag("secret-read-failed"), style = CottonTextStyles.pageTitle) } private data class VisibleSecretField(val field: PasswordFacts.Field, val value: String?) { override fun toString(): String = "VisibleSecretField(key=${field.key}, value=)" } private enum class SecretDetailAction { Trash, Restore } private fun secretFields(kind: SecretKind, payload: SecretPayload?): List { val opened = payload?.fieldsJson() return PasswordFacts.fields(kind) .map { field -> VisibleSecretField(field, (opened?.get(field.key) as? JsonPrimitive)?.content) } .filter { entry -> entry.field.isPrimary || (payload != null && entry.value != null) } } private fun metadataRows(secret: PasswordSecret, zoneId: ZoneId): List> = buildList { secret.username?.takeIf(String::isNotBlank)?.let { add("Username" to it) } secret.site?.takeIf(String::isNotBlank)?.let { add("Website" to it) } secret.service?.takeIf(String::isNotBlank)?.let { add("Service" to it) } secret.expiresAt?.let { spelledDate(it, zoneId) }?.let { add("Runs out" to it) } secret.lastUsedAt?.let { spelledDate(it, zoneId) }?.let { add("Last used" to it) } } private fun placementStatus(placement: PasswordPlacement, zoneId: ZoneId): String? { val prefix = placement.format.takeIf(String::isNotBlank) val status = placement.problem?.takeIf(String::isNotBlank) ?: placement.appliedAt?.let { spelledDate(it, zoneId) }?.let { "written $it" } ?: "waiting" return listOfNotNull(prefix, status).joinToString(" · ") } private fun spelledDate(iso: String, zoneId: ZoneId): String? = runCatching { Instant.parse(iso).atZone(zoneId).toLocalDate() .format(DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.US)) }.getOrNull() private fun updatedLine(iso: String, clock: Clock, zoneId: ZoneId): String? = runCatching { val instant = Instant.parse(iso) val date = instant.atZone(zoneId).toLocalDate() val pattern = if (date.year == clock.instant().atZone(zoneId).year) "d MMM" else "d MMM uuuu" "updated ${date.format(DateTimeFormatter.ofPattern(pattern, Locale.US))}" }.getOrNull() private fun maskedSecret(hint: String?): String = hint?.trim()?.takeIf { it.isNotEmpty() }?.let { "•••• $it" } ?: "••••••••" private fun SecretDetailState.detailRead(): PasswordSecretRead? = when (this) { is SecretDetailState.Data -> read is SecretDetailState.Error -> last SecretDetailState.Loading -> null }