package app.closer.ui.settings

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
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 androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
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.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,
    content: @Composable () -> Unit
) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(SettingsCard, RoundedCornerShape(16.dp))
            .padding(vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(4.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() {
    Divider(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
            ) {
                CircularProgressIndicator()
            }
        } 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 = 8.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // Profile card — editable identity (currently local-only)
                Card(
                    onClick = { onNavigate(AppRoute.ACCOUNT) },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard)
                ) {
                    Row(
                        modifier = Modifier.padding(16.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
                Card(
                    onClick = {
                        onNavigate(
                            if (state.isPaired) AppRoute.RELATIONSHIP_SETTINGS
                            else AppRoute.CREATE_INVITE
                        )
                    },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        ProfileAvatar(
                            imageUrl = state.partnerPhotoUrl,
                            fallbackIcon = if (state.isPaired) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
                            fallbackTint = if (state.isPaired) SettingsPrimaryDeep else SettingsMuted
                        )
                        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 = SettingsMuted,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                            if (state.isPaired) {
                                Text(
                                    text = state.partnerName ?: "Your partner",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold,
                                    color = SettingsInk,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            } else {
                                Text(
                                    text = "Invite someone to connect",
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = SettingsInk,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                        }
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowForwardIos,
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                            tint = SettingsPrimaryDeep
                        )
                    }
                }

                Spacer(Modifier.height(4.dp))

                SettingsSection(title = "For the two of you") {
                    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") {
                    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") {
                    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") {
                    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") {
                    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) CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = SettingsDanger,
                        strokeWidth = 2.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
) {
    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)
    ) {
        Icon(icon, contentDescription = null, tint = tint)
        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
                )
            }
        }
        Icon(
            Icons.AutoMirrored.Filled.ArrowForwardIos,
            contentDescription = null,
            modifier = Modifier.size(14.dp),
            tint = SettingsMuted
        )
    }
}
