package app.closer.ui.settings

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForwardIos
import androidx.compose.material.icons.automirrored.filled.TrendingUp
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Warning
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.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
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.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.core.navigation.AppRoute
import app.closer.domain.model.OutcomeDay
import app.closer.ui.components.OutcomeCheckInDialog
import app.closer.ui.theme.isCloserDarkTheme
import app.closer.ui.settings.SettingsDanger
import app.closer.ui.settings.SettingsInk
import app.closer.ui.settings.SettingsMuted
import app.closer.ui.settings.SettingsPrimaryDeep
import app.closer.ui.settings.SettingsSoft
import coil.compose.AsyncImage

// ====================
// Settings Subpages
// ====================

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsSubpage(
    title: String,
    onBack: () -> Unit,
    modifier: Modifier = Modifier,
    snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },
    content: @Composable (PaddingValues) -> Unit
) {
    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) },
        containerColor = Color.Transparent,
        modifier = modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = { Text(title, color = SettingsInk) },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                            tint = SettingsInk
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.background
                )
            )
        }
    ) { padding -> content(padding) }
}

@Composable
fun SettingsSection(
    title: String? = null,
    modifier: Modifier = Modifier,
    accent: Color = Color(0xFFF7C8E4),
    content: @Composable () -> Unit
) {
    val sectionAccent = if (isCloserDarkTheme()) {
        MaterialTheme.colorScheme.primaryContainer
    } else {
        accent
    }
    Card(
        modifier = modifier
            .fillMaxWidth(),
        shape = RoundedCornerShape(22.dp),
        colors = CardDefaults.cardColors(containerColor = sectionAccent.copy(alpha = 0.16f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 5.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(1.dp)
                .background(SettingsCard.copy(alpha = 0.92f), RoundedCornerShape(21.dp))
                .padding(vertical = 8.dp),
            verticalArrangement = Arrangement.spacedBy(2.dp)
        ) {
            title?.let {
                Text(
                    text = it,
                    style = MaterialTheme.typography.labelMedium,
                    color = SettingsMuted,
                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
                )
            }
            content()
        }
    }
}

@Composable
fun SettingsSectionDivider() {
    HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
}

// ====================
// Account State Models
// ====================

/** Signed-out local mode - no account data yet */
private data class SignedOutState(
    val displayName: String = "Guest",
    val email: String = "",
    val isPaired: Boolean = false,
    val partnerName: String? = null
)

/** Signed-in local mode - account exists but no pairing */
private data class SignedInUnpairedState(
    val displayName: String,
    val email: String,
    val isPaired: Boolean = false,
    val partnerName: String? = null
)

/** Signed-in paired state */
private data class SignedInPairedState(
    val displayName: String,
    val email: String,
    val isPaired: Boolean = true,
    val partnerName: String
)

/** Account state (use when real account data is ready) */
private data class AccountState(
    val displayName: String = "",
    val email: String = "",
    val isPaired: Boolean = false,
    val partnerName: String? = null
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: SettingsViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()
    val snackbar = remember { SnackbarHostState() }
    LaunchedEffect(state.navigateTo) {
        state.navigateTo?.let { onNavigate(it); viewModel.onNavigated() }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbar) },
        containerColor = Color.Transparent,
        modifier = Modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        "Settings",
                        style = MaterialTheme.typography.titleLarge,
                        color = SettingsInk
                    )
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.background
                )
            )
        }
    ) { padding ->
        if (state.isLoading) {
            Column(
                modifier = Modifier.fillMaxSize().padding(padding),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                CloserHeartLoader()
            }
        } else {
            var showBaselineOutcomeDialog by remember { mutableStateOf(false) }
            var showFollowUpOutcomeDialog by remember { mutableStateOf(false) }
            var pendingOutcomeDay by remember { mutableStateOf<OutcomeDay?>(null) }

            val followUp = state.outcomeFollowUpDay
            LaunchedEffect(state.isPaired, followUp) {
                if (state.isPaired) {
                    if (state.outcomeBaselineDialogDue) {
                        showBaselineOutcomeDialog = true
                    }
                    if (followUp != null) {
                        pendingOutcomeDay = followUp
                        showFollowUpOutcomeDialog = true
                    }
                }
            }

            if (showBaselineOutcomeDialog) {
                OutcomeCheckInDialog(
                    title = "Quick check-in",
                    subtitle = "Before you start, how are you feeling about your relationship right now?",
                    onDismiss = {
                        viewModel.markBaselineOutcomeShown()
                        showBaselineOutcomeDialog = false
                    },
                    onSubmit = { scores ->
                        viewModel.submitOutcome(OutcomeDay.BASELINE.key, scores)
                        showBaselineOutcomeDialog = false
                    }
                )
            }

            pendingOutcomeDay?.let { day ->
                if (showFollowUpOutcomeDialog) {
                    OutcomeCheckInDialog(
                        title = "${day.label} check-in",
                        subtitle = "How are you feeling now compared to when you started?",
                        onDismiss = {
                            viewModel.markFollowUpOutcomeShown(day.key)
                            showFollowUpOutcomeDialog = false
                            pendingOutcomeDay = null
                        },
                        onSubmit = { scores ->
                            viewModel.submitOutcome(day.key, scores)
                            showFollowUpOutcomeDialog = false
                            pendingOutcomeDay = null
                        }
                    )
                }
            }

            LaunchedEffect(state.outcomeSubmitSuccess) {
                if (state.outcomeSubmitSuccess) {
                    snackbar.showSnackbar("Check-in saved")
                    viewModel.consumeOutcomeSuccess()
                }
            }
            LaunchedEffect(state.outcomeError) {
                state.outcomeError?.let { snackbar.showSnackbar(it); viewModel.consumeOutcomeError() }
            }

            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .safeDrawingPadding()
                    .navigationBarsPadding()
                    .verticalScroll(rememberScrollState())
                    .padding(padding)
                    .padding(horizontal = 16.dp, vertical = 10.dp),
                verticalArrangement = Arrangement.spacedBy(14.dp)
            ) {
                Text(
                    text = "Manage your space, reminders, privacy, and account.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = SettingsMuted,
                    modifier = Modifier.padding(horizontal = 4.dp),
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )

                // Profile card — editable identity (currently local-only)
                Card(
                    onClick = { onNavigate(AppRoute.ACCOUNT) },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(22.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard.copy(alpha = 0.96f)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 5.dp)
                ) {
                    Row(
                        modifier = Modifier.padding(18.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        ProfileAvatar(
                            imageUrl = state.photoUrl,
                            fallbackIcon = Icons.Filled.Person,
                            fallbackTint = SettingsPrimaryDeep
                        )
                        Column(
                            modifier = Modifier.weight(1f),
                            verticalArrangement = Arrangement.spacedBy(2.dp)
                        ) {
                            Text(
                                text = state.displayName.ifBlank { "No name set" },
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold,
                                color = SettingsInk,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                            Text(
                                text = if (state.email.isNotBlank()) state.email else "Local profile — sign in to sync your account",
                                style = MaterialTheme.typography.bodySmall,
                                color = SettingsMuted,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowForwardIos,
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                            tint = SettingsPrimaryDeep
                        )
                    }
                }

                // Partner card — fully tappable, visually obvious
                val partnerCardColor = if (state.isPaired) {
                    SettingsSoft.copy(alpha = 0.52f)
                } else if (isCloserDarkTheme()) {
                    MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.74f)
                } else {
                    MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.46f)
                }
                val partnerAccent = if (state.isPaired) SettingsPrimaryDeep else MaterialTheme.colorScheme.secondary
                val partnerContentColor = if (state.isPaired) SettingsInk else MaterialTheme.colorScheme.onSecondaryContainer
                val partnerMutedColor = if (state.isPaired) SettingsMuted else MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.72f)
                Card(
                    onClick = {
                        onNavigate(
                            if (state.isPaired) AppRoute.RELATIONSHIP_SETTINGS
                            else AppRoute.CREATE_INVITE
                        )
                    },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(22.dp),
                    colors = CardDefaults.cardColors(containerColor = partnerCardColor),
                    border = if (state.isPaired) null else BorderStroke(1.dp, partnerAccent.copy(alpha = 0.18f)),
                    elevation = CardDefaults.cardElevation(defaultElevation = 5.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(18.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        if (state.isPaired) {
                            ProfileAvatar(
                                imageUrl = state.partnerPhotoUrl,
                                fallbackIcon = Icons.Filled.Favorite,
                                fallbackTint = SettingsPrimaryDeep
                            )
                        } else {
                            Box(
                                modifier = Modifier
                                    .size(48.dp)
                                    .clip(RoundedCornerShape(16.dp))
                                    .background(partnerAccent.copy(alpha = 0.13f)),
                                contentAlignment = Alignment.Center
                            ) {
                                Icon(
                                    Icons.Filled.FavoriteBorder,
                                    contentDescription = null,
                                    tint = partnerAccent,
                                    modifier = Modifier.size(24.dp)
                                )
                            }
                        }
                        Column(
                            modifier = Modifier.weight(1f),
                            verticalArrangement = Arrangement.spacedBy(2.dp)
                        ) {
                            Text(
                                text = if (state.isPaired) "Connected with" else "No partner yet",
                                style = MaterialTheme.typography.labelMedium,
                                color = partnerMutedColor,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                            if (state.isPaired) {
                                Text(
                                    text = state.partnerName ?: "Your partner",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold,
                                    color = partnerContentColor,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            } else {
                                Text(
                                    text = "Invite someone to connect",
                                    style = MaterialTheme.typography.titleSmall,
                                    fontWeight = FontWeight.SemiBold,
                                    color = partnerContentColor,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                        }
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowForwardIos,
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                            tint = partnerAccent
                        )
                    }
                }

                SettingsSection(title = "For the two of you", accent = Color(0xFFF7C8E4)) {
                    SettingsRow(
                        icon = Icons.Filled.Favorite,
                        label = "Together",
                        subtitle = "Your shared activity, answers, and milestones",
                        onClick = { onNavigate(AppRoute.ACTIVITY) },
                        badgeCount = state.unreadActivityCount
                    )
                    SettingsSectionDivider()
                    if (app.closer.BuildConfig.DEBUG) {
                        SettingsRow(
                            icon = Icons.Filled.Favorite,
                            label = "Art preview (debug)",
                            subtitle = "Preview celebration art without pairing",
                            onClick = { onNavigate(AppRoute.ART_PREVIEW) }
                        )
                        SettingsSectionDivider()
                        SettingsRow(
                            icon = Icons.Filled.Favorite,
                            label = "Paired home (debug)",
                            subtitle = "Preview the paired Home without pairing",
                            onClick = { onNavigate(AppRoute.PAIRED_HOME_PREVIEW) }
                        )
                        SettingsSectionDivider()
                    }
                    SettingsRow(
                        icon = Icons.Filled.Done,
                        label = "Answer History",
                        subtitle = "Revisit the moments you have shared",
                        onClick = { onNavigate(AppRoute.ANSWER_HISTORY) }
                    )
                    SettingsSectionDivider()
                    SettingsRow(
                        icon = Icons.AutoMirrored.Filled.TrendingUp,
                        label = "Your Progress",
                        subtitle = "See patterns, check-ins, and growth",
                        onClick = { onNavigate(AppRoute.YOUR_PROGRESS) }
                    )
                }

                SettingsSection(title = "Your rhythm", accent = Color(0xFFD9B8FF)) {
                    SettingsRow(
                        icon = Icons.Filled.Notifications,
                        label = "Notifications",
                        subtitle = "Set gentle reminders that fit your day",
                        onClick = { onNavigate(AppRoute.NOTIFICATIONS) }
                    )
                    SettingsSectionDivider()
                    SettingsRow(
                        icon = Icons.Filled.Palette,
                        label = "Appearance",
                        subtitle = "Make Closer feel comfortable to open",
                        onClick = { onNavigate(AppRoute.APPEARANCE) }
                    )
                }

                SettingsSection(title = "Premium", accent = Color(0xFFE7A2D1)) {
                    SettingsRow(
                        icon = Icons.Filled.Favorite,
                        label = "Subscription",
                        subtitle = "Manage one plan for both partners",
                        onClick = { onNavigate(AppRoute.SUBSCRIPTION) },
                        tint = SettingsPrimaryDeep
                    )
                }

                SettingsSection(title = "Privacy and safety", accent = Color(0xFFD9B8FF)) {
                    SettingsRow(
                        icon = Icons.Filled.Lock,
                        label = "Security",
                        subtitle = "Recovery phrase and account protection",
                        onClick = { onNavigate(AppRoute.SECURITY) }
                    )
                    SettingsSectionDivider()
                    SettingsRow(
                        icon = Icons.Filled.Lock,
                        label = "Privacy & Terms",
                        subtitle = "Your data, policies, and legal details",
                        onClick = { onNavigate(AppRoute.PRIVACY) }
                    )
                }

                SettingsSection(title = "Account", accent = Color(0xFFFFD9E8)) {
                    SettingsRow(
                        icon = Icons.Filled.Warning,
                        label = "Delete account",
                        subtitle = "Permanently remove your Closer account",
                        onClick = { onNavigate(AppRoute.DELETE_ACCOUNT) },
                        tint = SettingsDanger
                    )
                }

                Spacer(Modifier.height(8.dp))

                OutlinedButton(
                    onClick = viewModel::signOut,
                    enabled = !state.isSigningOut,
                    modifier = Modifier.fillMaxWidth().height(52.dp),
                    shape = RoundedCornerShape(12.dp),
                    colors = ButtonDefaults.outlinedButtonColors(
                        contentColor = SettingsDanger
                    )
                ) {
                    if (state.isSigningOut) CloserHeartLoader(size = 22.dp)
                    else Text("Sign out", style = MaterialTheme.typography.labelLarge)
                }

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

@Composable
private fun ProfileAvatar(
    imageUrl: String?,
    fallbackIcon: ImageVector,
    fallbackTint: androidx.compose.ui.graphics.Color,
    modifier: Modifier = Modifier
) {
    val cleanUrl = imageUrl?.takeIf { it.isNotBlank() }
    if (cleanUrl != null) {
        AsyncImage(
            model = cleanUrl,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            placeholder = rememberVectorPainter(fallbackIcon),
            error = rememberVectorPainter(fallbackIcon),
            modifier = modifier
                .size(48.dp)
                .clip(CircleShape)
                .border(1.5.dp, SettingsSoft, CircleShape)
        )
    } else {
        Icon(
            fallbackIcon,
            contentDescription = null,
            modifier = modifier.size(40.dp),
            tint = fallbackTint
        )
    }
}

@Composable
private fun SettingsRow(
    icon: ImageVector,
    label: String,
    subtitle: String? = null,
    onClick: () -> Unit,
    tint: androidx.compose.ui.graphics.Color = SettingsMuted,
    badgeCount: Int = 0
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = if (subtitle == null) 14.dp else 12.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        androidx.compose.foundation.layout.Box(
            modifier = Modifier
                .size(40.dp)
                .clip(RoundedCornerShape(14.dp))
                .background(tint.copy(alpha = if (tint == SettingsDanger) 0.12f else 0.14f)),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                icon,
                contentDescription = null,
                tint = tint,
                modifier = Modifier.size(20.dp)
            )
        }
        Column(
            modifier = Modifier.weight(1f),
            verticalArrangement = Arrangement.spacedBy(2.dp)
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyLarge,
                color = if (tint == SettingsMuted) SettingsInk else tint,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            subtitle?.let {
                Text(
                    text = it,
                    style = MaterialTheme.typography.bodySmall,
                    color = SettingsMuted,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        if (badgeCount > 0) {
            androidx.compose.foundation.layout.Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(999.dp))
                    .background(Color(0xFF8F67C5))
                    .padding(horizontal = 8.dp, vertical = 2.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = if (badgeCount > 9) "9+" else badgeCount.toString(),
                    style = MaterialTheme.typography.labelSmall,
                    color = Color.White
                )
            }
        }
        Icon(
            Icons.AutoMirrored.Filled.ArrowForwardIos,
            contentDescription = null,
            modifier = Modifier.size(14.dp),
            tint = SettingsMuted
        )
    }
}
