package app.closer.ui.memorylane

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
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.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.LockOpen
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.CouplePremiumChecker
import app.closer.core.navigation.AppRoute
import app.closer.data.remote.FirestoreCapsuleDataSource
import app.closer.domain.model.TimeCapsule
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
import app.closer.ui.theme.CloserPalette
import app.closer.ui.theme.closerBackgroundBrush
import dagger.hilt.android.lifecycle.HiltViewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

// ── Unlock presets ─────────────────────────────────────────────────────────────

enum class UnlockPreset(val label: String, val ms: Long) {
    ONE_MONTH("1 month", 30L * 86_400_000),
    THREE_MONTHS("3 months", 90L * 86_400_000),
    SIX_MONTHS("6 months", 180L * 86_400_000),
    ONE_YEAR("1 year", 365L * 86_400_000),
    TWO_YEARS("2 years", 730L * 86_400_000)
}

private val capsulePrompts = listOf(
    "What are you most proud of in your relationship right now?",
    "Write a letter to your partner for them to read when this opens.",
    "What do you hope has changed — and what do you hope has stayed the same?",
    "Describe where you are in your relationship today, honestly.",
    "What's something small about right now that you never want to forget?",
    "What challenge are you facing together, and how are you handling it?",
    "If your future self reads this, what do you most want them to know?"
)

// ── ViewModel ──────────────────────────────────────────────────────────────────

enum class MemoryLanePhase { LOADING, LIST, CREATE, EDIT, DETAIL, ERROR }

data class MemoryLaneUiState(
    val phase: MemoryLanePhase = MemoryLanePhase.LOADING,
    val capsules: List<TimeCapsule> = emptyList(),
    val coupleId: String? = null,
    val userId: String? = null,
    val selectedCapsule: TimeCapsule? = null,
    // create form
    val createTitle: String = "",
    val createContent: String = "",
    val selectedPreset: UnlockPreset = UnlockPreset.ONE_YEAR,
    val selectedPrompt: String? = null,
    val customUnlockMs: Long? = null,
    val showDatePicker: Boolean = false,
    val showDeleteConfirm: Boolean = false,
    val isSaving: Boolean = false,
    val isDeleting: Boolean = false,
    val error: String? = null,
    val hasPremium: Boolean = true,
    val navigateTo: String? = null
)

@HiltViewModel
class MemoryLaneViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository,
    private val capsuleDataSource: FirestoreCapsuleDataSource,
    private val premiumChecker: CouplePremiumChecker
) : ViewModel() {

    private val _uiState = MutableStateFlow(MemoryLaneUiState())
    val uiState: StateFlow<MemoryLaneUiState> = _uiState.asStateFlow()

    init {
        load()
    }

    private fun load() {
        viewModelScope.launch {
            val hasPremium = premiumChecker.hasPremium()
            if (!hasPremium) {
                _uiState.update { it.copy(phase = MemoryLanePhase.LIST, hasPremium = false) }
                return@launch
            }

            val uid = authRepository.currentUserId ?: run {
                _uiState.update { it.copy(phase = MemoryLanePhase.ERROR, error = "Sign in to view Memory Lane.") }
                return@launch
            }
            val couple = coupleRepository.getCoupleForUser(uid) ?: run {
                _uiState.update { it.copy(navigateTo = AppRoute.CREATE_INVITE) }
                return@launch
            }

            _uiState.update { it.copy(coupleId = couple.id, userId = uid, hasPremium = true) }

            runCatching {
                capsuleDataSource.observeCapsules(couple.id).collect { capsules ->
                    capsules.filter { it.status == "sealed" && System.currentTimeMillis() >= it.unlockAt }
                        .forEach { capsule ->
                            viewModelScope.launch {
                                runCatching { capsuleDataSource.unlockCapsule(couple.id, capsule.id) }
                            }
                        }
                    _uiState.update { it.copy(phase = MemoryLanePhase.LIST, capsules = capsules) }
                }
            }.onFailure { e ->
                Log.w(TAG, "Failed to observe capsules", e)
                _uiState.update { it.copy(phase = MemoryLanePhase.ERROR, error = "Couldn't load your capsules. Try again.") }
            }
        }
    }

    fun retry() {
        _uiState.update { it.copy(phase = MemoryLanePhase.LOADING, error = null) }
        load()
    }

    fun onNavigated() = _uiState.update { it.copy(navigateTo = null) }

    fun openCreate() = _uiState.update {
        it.copy(
            phase = MemoryLanePhase.CREATE,
            createTitle = "",
            createContent = "",
            selectedPreset = UnlockPreset.ONE_YEAR,
            selectedPrompt = null,
            customUnlockMs = null,
            showDatePicker = false,
            error = null
        )
    }

    fun openDetail(capsule: TimeCapsule) =
        _uiState.update { it.copy(phase = MemoryLanePhase.DETAIL, selectedCapsule = capsule) }

    fun backToList() = _uiState.update { it.copy(phase = MemoryLanePhase.LIST, selectedCapsule = null) }

    fun updateTitle(v: String) = _uiState.update { it.copy(createTitle = v) }
    fun updateContent(v: String) = _uiState.update { it.copy(createContent = v) }
    fun selectPreset(p: UnlockPreset) = _uiState.update { it.copy(selectedPreset = p, customUnlockMs = null) }
    fun showDatePicker() = _uiState.update { it.copy(showDatePicker = true) }
    fun hideDatePicker() = _uiState.update { it.copy(showDatePicker = false) }
    fun selectCustomDate(epochMs: Long) = _uiState.update { it.copy(customUnlockMs = epochMs, showDatePicker = false) }
    fun selectPrompt(p: String?) = _uiState.update {
        it.copy(selectedPrompt = p, createContent = if (p != null) "" else it.createContent)
    }

    fun saveCapsule() {
        val state = _uiState.value
        val coupleId = state.coupleId ?: return
        val userId = state.userId ?: return
        if (state.createTitle.isBlank()) {
            _uiState.update { it.copy(error = "Give your capsule a title.") }
            return
        }
        if (state.createContent.isBlank()) {
            _uiState.update { it.copy(error = "Write something inside.") }
            return
        }
        _uiState.update { it.copy(isSaving = true, error = null) }
        val now = System.currentTimeMillis()
        val capsule = TimeCapsule(
            coupleId = coupleId,
            authorId = userId,
            title = state.createTitle.trim(),
            content = state.createContent.trim(),
            promptUsed = state.selectedPrompt,
            unlockAt = state.customUnlockMs ?: (now + state.selectedPreset.ms),
            createdAt = now,
            status = "sealed"
        )
        viewModelScope.launch {
            runCatching { capsuleDataSource.createCapsule(capsule) }
                .onSuccess { _uiState.update { it.copy(isSaving = false, phase = MemoryLanePhase.LIST) } }
                .onFailure { e ->
                    Log.w(TAG, "Could not save capsule", e)
                    val msg = if (e is IllegalStateException) e.message ?: "Encryption not ready. Try again." else "Could not save. Check your connection."
                    _uiState.update { s -> s.copy(isSaving = false, error = msg) }
                }
        }
    }

    fun openEdit(capsule: TimeCapsule) = _uiState.update {
        it.copy(
            phase = MemoryLanePhase.EDIT,
            selectedCapsule = capsule,
            createTitle = capsule.title,
            createContent = capsule.content,
            selectedPrompt = capsule.promptUsed,
            customUnlockMs = capsule.unlockAt,
            showDatePicker = false,
            error = null
        )
    }

    fun saveEdit() {
        val state = _uiState.value
        val capsule = state.selectedCapsule ?: return
        val coupleId = state.coupleId ?: return
        if (state.createTitle.isBlank()) {
            _uiState.update { it.copy(error = "Give your capsule a title.") }
            return
        }
        if (state.createContent.isBlank()) {
            _uiState.update { it.copy(error = "Write something inside.") }
            return
        }
        _uiState.update { it.copy(isSaving = true, error = null) }
        val updated = capsule.copy(
            title = state.createTitle.trim(),
            content = state.createContent.trim(),
            promptUsed = state.selectedPrompt,
            unlockAt = state.customUnlockMs ?: capsule.unlockAt
        )
        viewModelScope.launch {
            runCatching { capsuleDataSource.updateCapsule(updated) }
                .onSuccess { _uiState.update { it.copy(isSaving = false, phase = MemoryLanePhase.LIST, selectedCapsule = null) } }
                .onFailure { e ->
                    Log.w(TAG, "Could not update capsule", e)
                    val msg = if (e is IllegalStateException) e.message ?: "Encryption not ready. Try again." else "Could not save. Check your connection."
                    _uiState.update { s -> s.copy(isSaving = false, error = msg) }
                }
        }
    }

    fun showDeleteConfirm() = _uiState.update { it.copy(showDeleteConfirm = true) }
    fun dismissDeleteConfirm() = _uiState.update { it.copy(showDeleteConfirm = false) }

    fun deleteCapsule() {
        val state = _uiState.value
        val capsule = state.selectedCapsule ?: return
        val coupleId = state.coupleId ?: return
        _uiState.update { it.copy(showDeleteConfirm = false, isDeleting = true) }
        viewModelScope.launch {
            runCatching { capsuleDataSource.deleteCapsule(coupleId, capsule.id) }
                .onSuccess { _uiState.update { it.copy(isDeleting = false, phase = MemoryLanePhase.LIST, selectedCapsule = null) } }
                .onFailure { e ->
                    Log.w(TAG, "Could not delete capsule", e)
                    _uiState.update { s -> s.copy(isDeleting = false, error = "Could not delete. Check your connection and try again.") }
                }
        }
    }

    fun dismissError() = _uiState.update { it.copy(error = null) }

    companion object {
        private const val TAG = "MemoryLaneViewModel"
    }
}

// ── Screen ─────────────────────────────────────────────────────────────────────

@Composable
fun MemoryLaneScreen(
    onNavigate: (String) -> Unit = {},
    startingCapsuleId: String? = null,
    viewModel: MemoryLaneViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }

    // Deep-link: open a specific capsule once the list is loaded. The flag prevents
    // re-opening if the user navigates back to the list and capsules update again.
    val deepLinkHandled = remember { mutableStateOf(false) }
    LaunchedEffect(startingCapsuleId, state.capsules) {
        if (startingCapsuleId == null || deepLinkHandled.value) return@LaunchedEffect
        if (state.capsules.isEmpty()) return@LaunchedEffect
        val capsule = state.capsules.firstOrNull { it.id == startingCapsuleId }
        if (capsule != null) {
            deepLinkHandled.value = true
            viewModel.openDetail(capsule)
        }
    }

    LaunchedEffect(state.navigateTo) {
        state.navigateTo?.let { onNavigate(it); viewModel.onNavigated() }
    }
    // Show snackbar only for DETAIL-phase errors (create/edit have inline error display).
    LaunchedEffect(state.error, state.phase) {
        val msg = state.error
        if (state.phase == MemoryLanePhase.DETAIL && msg != null) {
            snackbarHostState.showSnackbar(msg)
            viewModel.dismissError()
        }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) },
        containerColor = Color.Transparent
    ) { padding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .background(closerBackgroundBrush())
        ) {
            when (state.phase) {
                MemoryLanePhase.LOADING -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CloserHeartLoader()
                }
                MemoryLanePhase.LIST -> if (!state.hasPremium) {
                    MemoryLaneLockedScreen(
                        onBack = { onNavigate(AppRoute.PLAY) },
                        onUnlock = { onNavigate(AppRoute.PAYWALL) }
                    )
                } else {
                    CapsuleListScreen(
                        capsules = state.capsules,
                        onBack = { onNavigate(AppRoute.PLAY) },
                        onNew = { viewModel.openCreate() },
                        onOpen = { viewModel.openDetail(it) }
                    )
                }
                MemoryLanePhase.CREATE -> CapsuleCreateScreen(
                    state = state,
                    isEditing = false,
                    onBack = { viewModel.backToList() },
                    onTitleChange = { viewModel.updateTitle(it) },
                    onContentChange = { viewModel.updateContent(it) },
                    onPresetSelect = { viewModel.selectPreset(it) },
                    onPromptSelect = { viewModel.selectPrompt(it) },
                    onShowDatePicker = { viewModel.showDatePicker() },
                    onDatePicked = { viewModel.selectCustomDate(it) },
                    onHideDatePicker = { viewModel.hideDatePicker() },
                    onSave = { viewModel.saveCapsule() }
                )
                MemoryLanePhase.EDIT -> CapsuleCreateScreen(
                    state = state,
                    isEditing = true,
                    onBack = { viewModel.backToList() },
                    onTitleChange = { viewModel.updateTitle(it) },
                    onContentChange = { viewModel.updateContent(it) },
                    onPresetSelect = { viewModel.selectPreset(it) },
                    onPromptSelect = { viewModel.selectPrompt(it) },
                    onShowDatePicker = { viewModel.showDatePicker() },
                    onDatePicked = { viewModel.selectCustomDate(it) },
                    onHideDatePicker = { viewModel.hideDatePicker() },
                    onSave = { viewModel.saveEdit() }
                )
                MemoryLanePhase.DETAIL -> {
                    val capsule = state.selectedCapsule
                    if (capsule != null) {
                        CapsuleDetailScreen(
                            capsule = capsule,
                            userId = state.userId ?: "",
                            onBack = { viewModel.backToList() },
                            onEdit = if (!capsule.isUnlocked && capsule.authorId == state.userId) {
                                { viewModel.openEdit(capsule) }
                            } else null,
                            onDelete = if (capsule.authorId == state.userId) {
                                { viewModel.showDeleteConfirm() }
                            } else null,
                            showDeleteConfirm = state.showDeleteConfirm,
                            isDeleting = state.isDeleting,
                            onConfirmDelete = { viewModel.deleteCapsule() },
                            onDismissDelete = { viewModel.dismissDeleteConfirm() }
                        )
                    } else {
                        LaunchedEffect(Unit) { viewModel.backToList() }
                    }
                }
                MemoryLanePhase.ERROR -> MemoryLaneErrorScreen(
                    message = state.error ?: "Something went wrong.",
                    onBack = { onNavigate(AppRoute.PLAY) },
                    onRetry = { viewModel.retry() }
                )
            }
        }
    }
}

// ── Locked ─────────────────────────────────────────────────────────────────────

@Composable
private fun MemoryLaneLockedScreen(onBack: () -> Unit, onUnlock: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding()
            .padding(horizontal = 28.dp, vertical = 32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Surface(shape = RoundedCornerShape(50.dp), color = CloserPalette.Romantic.copy(alpha = 0.12f)) {
            Icon(
                Icons.Filled.Lock,
                contentDescription = null,
                modifier = Modifier.padding(20.dp).size(32.dp),
                tint = CloserPalette.Romantic
            )
        }
        Spacer(Modifier.height(20.dp))
        Text("Memory Lane is a premium feature", style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center)
        Spacer(Modifier.height(10.dp))
        Text("Write notes to your future selves — sealed until the date you choose.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center)
        Spacer(Modifier.height(28.dp))
        Button(onClick = onUnlock, modifier = Modifier.fillMaxWidth().heightIn(min = 54.dp), shape = RoundedCornerShape(18.dp), colors = ButtonDefaults.buttonColors(containerColor = CloserPalette.Romantic)) {
            Text("Unlock premium", color = Color.White, style = MaterialTheme.typography.labelLarge)
        }
        TextButton(onClick = onBack) { Text("Go back") }
    }
}

// ── Error ──────────────────────────────────────────────────────────────────────

@Composable
private fun MemoryLaneErrorScreen(message: String, onBack: () -> Unit, onRetry: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding()
            .padding(horizontal = 28.dp, vertical = 32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text("📦", style = MaterialTheme.typography.displayMedium)
        Spacer(Modifier.height(16.dp))
        Text(message, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center)
        Spacer(Modifier.height(24.dp))
        Button(onClick = onRetry, shape = RoundedCornerShape(16.dp), colors = ButtonDefaults.buttonColors(containerColor = CloserPalette.PurpleDeep)) {
            Text("Try again", color = Color.White)
        }
        TextButton(onClick = onBack) { Text("Go back") }
    }
}

// ── List ───────────────────────────────────────────────────────────────────────

@Composable
private fun CapsuleListScreen(
    capsules: List<TimeCapsule>,
    onBack: () -> Unit,
    onNew: () -> Unit,
    onOpen: (TimeCapsule) -> Unit
) {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding(),
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onBack) {
                    Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back", tint = MaterialTheme.colorScheme.onBackground)
                }
                Spacer(Modifier.width(4.dp))
                Column(modifier = Modifier.weight(1f)) {
                    Text("Memory Lane", style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onBackground)
                    Text("Notes that open on a future date.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
                IconButton(onClick = onNew) {
                    Surface(shape = RoundedCornerShape(12.dp), color = CloserPalette.PurpleDeep) {
                        Icon(Icons.Filled.Add, contentDescription = "New capsule", tint = Color.White, modifier = Modifier.padding(6.dp).size(20.dp))
                    }
                }
            }
        }

        if (capsules.isEmpty()) {
            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 48.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text("📦", style = MaterialTheme.typography.displayMedium)
                    Text("No capsules yet", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onSurface)
                    Text("Write a note to your future selves — it'll stay sealed until the date you choose.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center)
                    Spacer(Modifier.height(8.dp))
                    Button(onClick = onNew, shape = RoundedCornerShape(16.dp), colors = ButtonDefaults.buttonColors(containerColor = CloserPalette.PurpleDeep)) {
                        Text("Write your first capsule", color = Color.White)
                    }
                }
            }
        } else {
            items(capsules) { capsule ->
                CapsuleCard(capsule = capsule, onClick = { onOpen(capsule) })
            }
            item {
                TextButton(onClick = onNew, modifier = Modifier.fillMaxWidth()) {
                    Icon(Icons.Filled.Add, contentDescription = null, modifier = Modifier.size(16.dp))
                    Spacer(Modifier.width(6.dp))
                    Text("Add another capsule")
                }
            }
        }

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

@Composable
private fun CapsuleCard(capsule: TimeCapsule, onClick: () -> Unit) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            val unlocked = capsule.isUnlocked
            Surface(
                shape = RoundedCornerShape(14.dp),
                color = if (unlocked) CloserPalette.Evergreen.copy(alpha = 0.12f) else CloserPalette.PurpleDeep.copy(alpha = 0.10f),
                modifier = Modifier.size(48.dp)
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        imageVector = if (unlocked) Icons.Filled.LockOpen else Icons.Filled.Lock,
                        contentDescription = null,
                        tint = if (unlocked) CloserPalette.Evergreen else CloserPalette.PurpleDeep,
                        modifier = Modifier.size(22.dp)
                    )
                }
            }
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
                Text(capsule.title, style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis)
                if (unlocked) {
                    Text("Opened ${formatDate(capsule.unlockAt)}", style = MaterialTheme.typography.bodySmall, color = CloserPalette.Evergreen)
                } else {
                    Text("Opens ${countdown(capsule.unlockAt)}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
        }
    }
}

// ── Create ─────────────────────────────────────────────────────────────────────

@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
@Composable
private fun CapsuleCreateScreen(
    state: MemoryLaneUiState,
    isEditing: Boolean,
    onBack: () -> Unit,
    onTitleChange: (String) -> Unit,
    onContentChange: (String) -> Unit,
    onPresetSelect: (UnlockPreset) -> Unit,
    onPromptSelect: (String?) -> Unit,
    onShowDatePicker: () -> Unit,
    onDatePicked: (Long) -> Unit,
    onHideDatePicker: () -> Unit,
    onSave: () -> Unit
) {
    if (state.showDatePicker) {
        val pickerState = rememberDatePickerState(
            initialSelectedDateMillis = state.customUnlockMs ?: (System.currentTimeMillis() + UnlockPreset.ONE_YEAR.ms)
        )
        DatePickerDialog(
            onDismissRequest = onHideDatePicker,
            confirmButton = {
                TextButton(onClick = {
                    val ms = pickerState.selectedDateMillis
                    if (ms != null && ms > System.currentTimeMillis()) onDatePicked(ms)
                    else onHideDatePicker()
                }) { Text("OK") }
            },
            dismissButton = { TextButton(onClick = onHideDatePicker) { Text("Cancel") } }
        ) {
            DatePicker(state = pickerState)
        }
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Header
        Row(verticalAlignment = Alignment.CenterVertically) {
            IconButton(onClick = onBack) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back", tint = MaterialTheme.colorScheme.onBackground)
            }
            Spacer(Modifier.width(4.dp))
            Text(if (isEditing) "Edit Capsule" else "New Capsule", style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onBackground)
        }

        // Title field
        OutlinedTextField(
            value = state.createTitle,
            onValueChange = onTitleChange,
            label = { Text("Title") },
            placeholder = { Text("e.g. Letter to us") },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(16.dp),
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = CloserPalette.PurpleDeep,
                focusedLabelColor = CloserPalette.PurpleDeep
            )
        )

        // Optional prompt selector
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Text("Need a prompt?", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
            FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
                capsulePrompts.forEach { prompt ->
                    val selected = state.selectedPrompt == prompt
                    FilterChip(
                        selected = selected,
                        onClick = { onPromptSelect(if (selected) null else prompt) },
                        label = { Text(prompt.take(36) + if (prompt.length > 36) "…" else "", style = MaterialTheme.typography.labelSmall) },
                        colors = FilterChipDefaults.filterChipColors(
                            selectedContainerColor = CloserPalette.PurpleDeep.copy(alpha = 0.15f),
                            selectedLabelColor = CloserPalette.PurpleDeep
                        )
                    )
                }
            }
        }

        // Content field
        if (state.selectedPrompt != null) {
            Card(shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = CloserPalette.PurpleDeep.copy(alpha = 0.07f))) {
                Text(state.selectedPrompt, modifier = Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface)
            }
        }
        OutlinedTextField(
            value = state.createContent,
            onValueChange = onContentChange,
            label = { Text(if (state.selectedPrompt != null) "Your answer" else "What do you want to remember?") },
            minLines = 5,
            maxLines = 12,
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(16.dp),
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = CloserPalette.PurpleDeep,
                focusedLabelColor = CloserPalette.PurpleDeep
            )
        )

        // Unlock date presets + custom date
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Text("Open on", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
            FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
                UnlockPreset.entries.forEach { preset ->
                    FilterChip(
                        selected = state.customUnlockMs == null && state.selectedPreset == preset,
                        onClick = { onPresetSelect(preset) },
                        label = { Text(preset.label, style = MaterialTheme.typography.labelSmall) },
                        colors = FilterChipDefaults.filterChipColors(
                            selectedContainerColor = CloserPalette.PurpleDeep.copy(alpha = 0.15f),
                            selectedLabelColor = CloserPalette.PurpleDeep
                        )
                    )
                }
                FilterChip(
                    selected = state.customUnlockMs != null,
                    onClick = onShowDatePicker,
                    label = {
                        Text(
                            if (state.customUnlockMs != null) formatDate(state.customUnlockMs) else "Custom date",
                            style = MaterialTheme.typography.labelSmall
                        )
                    },
                    colors = FilterChipDefaults.filterChipColors(
                        selectedContainerColor = CloserPalette.PurpleDeep.copy(alpha = 0.15f),
                        selectedLabelColor = CloserPalette.PurpleDeep
                    )
                )
            }
            val previewMs = state.customUnlockMs ?: (System.currentTimeMillis() + state.selectedPreset.ms)
            Text(
                text = "Will open on ${formatDate(previewMs)}",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        // Error
        if (state.error != null) {
            Text(state.error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
        }

        // Save button
        Button(
            onClick = onSave,
            enabled = !state.isSaving,
            modifier = Modifier.fillMaxWidth().heightIn(min = 54.dp),
            shape = RoundedCornerShape(18.dp),
            colors = ButtonDefaults.buttonColors(containerColor = CloserPalette.PurpleDeep)
        ) {
            if (state.isSaving) CloserHeartLoader(size = 22.dp)
            else Text(if (isEditing) "Save changes" else "Seal the capsule 📦", color = Color.White, style = MaterialTheme.typography.labelLarge)
        }

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

// ── Detail ─────────────────────────────────────────────────────────────────────

@Composable
private fun CapsuleDetailScreen(
    capsule: TimeCapsule,
    userId: String,
    onBack: () -> Unit,
    onEdit: (() -> Unit)?,
    onDelete: (() -> Unit)?,
    showDeleteConfirm: Boolean,
    isDeleting: Boolean,
    onConfirmDelete: () -> Unit,
    onDismissDelete: () -> Unit
) {
    if (showDeleteConfirm) {
        AlertDialog(
            onDismissRequest = onDismissDelete,
            title = { Text("Delete capsule?") },
            text = { Text("This cannot be undone. The capsule and its contents will be permanently removed.") },
            confirmButton = {
                TextButton(onClick = onConfirmDelete) { Text("Delete", color = MaterialTheme.colorScheme.error) }
            },
            dismissButton = {
                TextButton(onClick = onDismissDelete) { Text("Cancel") }
            }
        )
    }

    val unlocked = capsule.isUnlocked
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .safeDrawingPadding()
            .navigationBarsPadding(),
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        item {
            Row(verticalAlignment = Alignment.CenterVertically) {
                IconButton(onClick = onBack) {
                    Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back", tint = MaterialTheme.colorScheme.onBackground)
                }
                Spacer(Modifier.width(4.dp))
                Column(modifier = Modifier.weight(1f)) {
                    Text(capsule.title, style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
                    Text(
                        text = if (capsule.authorId == userId) "Written by you" else "Written by your partner",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                if (onEdit != null) {
                    IconButton(onClick = onEdit, enabled = !isDeleting) {
                        Icon(Icons.Filled.Edit, contentDescription = "Edit", tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(20.dp))
                    }
                }
                if (onDelete != null) {
                    IconButton(onClick = onDelete, enabled = !isDeleting) {
                        if (isDeleting) CloserHeartLoader(size = 20.dp)
                        else Icon(Icons.Filled.Delete, contentDescription = "Delete", tint = MaterialTheme.colorScheme.error.copy(alpha = 0.7f), modifier = Modifier.size(20.dp))
                    }
                }
            }
        }

        if (unlocked) {
            item {
                Surface(shape = RoundedCornerShape(999.dp), color = CloserPalette.Evergreen.copy(alpha = 0.12f)) {
                    Row(modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                        Icon(Icons.Filled.LockOpen, contentDescription = null, tint = CloserPalette.Evergreen, modifier = Modifier.size(14.dp))
                        Text("Opened ${formatDate(capsule.unlockAt)}", style = MaterialTheme.typography.labelSmall, color = CloserPalette.Evergreen, fontWeight = FontWeight.SemiBold)
                    }
                }
            }

            if (capsule.promptUsed != null) {
                item {
                    Card(shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = CloserPalette.PurpleDeep.copy(alpha = 0.07f))) {
                        Text(capsule.promptUsed, modifier = Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                }
            }

            item {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(20.dp),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(modifier = Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Text(capsule.content, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface, lineHeight = MaterialTheme.typography.bodyLarge.lineHeight)
                        Text("Written ${formatDate(capsule.createdAt)}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                }
            }
        } else {
            item {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(20.dp),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(
                        modifier = Modifier.fillMaxWidth().padding(28.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Icon(Icons.Filled.Lock, contentDescription = null, tint = CloserPalette.PurpleDeep.copy(alpha = 0.5f), modifier = Modifier.size(40.dp))
                        Text("Still sealed", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center)
                        Text(
                            text = "Opens ${countdown(capsule.unlockAt)} — ${formatDate(capsule.unlockAt)}",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
        }

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

// ── Helpers ───────────────────────────────────────────────────────────────────

private val dateFmt = SimpleDateFormat("MMM d, yyyy", Locale.US)

private fun formatDate(ms: Long): String = dateFmt.format(Date(ms))

private fun countdown(unlockAt: Long): String {
    val diff = unlockAt - System.currentTimeMillis()
    if (diff <= 0) return "now"
    val days = TimeUnit.MILLISECONDS.toDays(diff)
    return when {
        days >= 365 -> "in ${days / 365} yr"
        days >= 30 -> "in ${days / 30} mo"
        days == 1L -> "tomorrow"
        else -> "in $days days"
    }
}
