package app.closer.ui.settings

import androidx.compose.foundation.background
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.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.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.Person
import androidx.compose.material.icons.filled.Star
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.RadioButton
import androidx.compose.material3.Scaffold
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
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 android.content.Context
import androidx.compose.ui.platform.LocalContext
import app.closer.core.navigation.AppRoute
import app.closer.core.navigation.ExternalLinks
import app.closer.domain.repository.ThemeMode
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

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

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsSubpage(
    title: String,
    onBack: () -> Unit,
    modifier: Modifier = Modifier,
    content: @Composable (PaddingValues) -> Unit
) {
    Scaffold(
        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 = Color.Transparent)
            )
        }
    ) { 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()

    LaunchedEffect(state.navigateTo) {
        state.navigateTo?.let { onNavigate(it); viewModel.onNavigated() }
    }

    Scaffold(
        containerColor = Color.Transparent,
        modifier = Modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        "Settings",
                        style = MaterialTheme.typography.titleLarge,
                        color = SettingsInk
                    )
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
            )
        }
    ) { padding ->
        if (state.isLoading) {
            Column(
                modifier = Modifier.fillMaxSize().padding(padding),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                CircularProgressIndicator()
            }
        } else {
            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)
                    ) {
                        Icon(
                            Icons.Filled.Person,
                            contentDescription = null,
                            modifier = Modifier.size(40.dp),
                            tint = 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)
                    ) {
                        Icon(
                            if (state.isPaired) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
                            contentDescription = null,
                            modifier = Modifier.size(40.dp),
                            tint = 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))

                Text(
                    text = "Appearance",
                    style = MaterialTheme.typography.labelLarge,
                    color = SettingsMuted,
                    modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp)
                )

                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard)
                ) {
                    Column {
                        ThemeModeRow(
                            label = "Device",
                            description = "Match your device appearance",
                            selected = state.themeMode == ThemeMode.DEVICE,
                            onClick = { viewModel.setThemeMode(ThemeMode.DEVICE) }
                        )
                        Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                        ThemeModeRow(
                            label = "Light",
                            description = "Always use light mode",
                            selected = state.themeMode == ThemeMode.LIGHT,
                            onClick = { viewModel.setThemeMode(ThemeMode.LIGHT) }
                        )
                        Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                        ThemeModeRow(
                            label = "Dark",
                            description = "Always use dark mode",
                            selected = state.themeMode == ThemeMode.DARK,
                            onClick = { viewModel.setThemeMode(ThemeMode.DARK) }
                        )
                    }
                }

                Spacer(Modifier.height(4.dp))

                // General section
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard)
                ) {
                    Column {
                        SettingsRow(
                            icon = Icons.Filled.Done,
                            label = "Answer History",
                            onClick = { onNavigate(AppRoute.ANSWER_HISTORY) }
                        )
                        Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                        SettingsRow(
                            icon = Icons.Filled.Notifications,
                            label = "Notifications",
                            onClick = { onNavigate(AppRoute.NOTIFICATIONS) }
                        )
                        Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                        SettingsRow(
                            icon = Icons.Filled.Star,
                            label = "Subscription",
                            onClick = { onNavigate(AppRoute.SUBSCRIPTION) }
                        )
                        Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                        SettingsRow(
                            icon = Icons.Filled.Lock,
                            label = "Privacy & Terms",
                            onClick = { onNavigate(AppRoute.PRIVACY) }
                        )
                    }
                }

                Spacer(Modifier.height(8.dp))

                // Legal
                Text(
                    text = "Legal",
                    style = MaterialTheme.typography.labelLarge,
                    color = SettingsMuted,
                    modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp)
                )

                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard)
                ) {
                    val context = LocalContext.current
                    Column {
                        SettingsLegalRow(
                            label = "Privacy Policy",
                            onClick = { ExternalLinks.openUrl(context, ExternalLinks.PRIVACY_POLICY) }
                        )
                        Divider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp)
                        SettingsLegalRow(
                            label = "Terms of Service",
                            onClick = { ExternalLinks.openUrl(context, ExternalLinks.TERMS_OF_SERVICE) }
                        )
                    }
                }

                Spacer(Modifier.height(8.dp))

                // Account lifecycle — separated from legal links
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(containerColor = SettingsCard)
                ) {
                    Column {
                        SettingsRow(
                            icon = Icons.Filled.Warning,
                            label = "Delete 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 ThemeModeRow(
    label: String,
    description: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 10.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        RadioButton(selected = selected, onClick = onClick)
        Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyLarge,
                color = SettingsInk
            )
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall,
                color = SettingsMuted
            )
        }
    }
}

@Composable
private fun SettingsRow(
    icon: ImageVector,
    label: String,
    onClick: () -> Unit,
    tint: androidx.compose.ui.graphics.Color = SettingsMuted
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Icon(icon, contentDescription = null, tint = tint)
        Text(
            text = label,
            style = MaterialTheme.typography.bodyLarge,
            color = if (tint == SettingsMuted) SettingsInk else tint,
            modifier = Modifier.weight(1f),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Icon(
            Icons.AutoMirrored.Filled.ArrowForwardIos,
            contentDescription = null,
            modifier = Modifier.size(14.dp),
            tint = SettingsMuted
        )
    }
}

@Composable
private fun SettingsLegalRow(
    label: String,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyLarge,
            color = SettingsInk,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Icon(
            Icons.AutoMirrored.Filled.ArrowForwardIos,
            contentDescription = null,
            modifier = Modifier.size(14.dp),
            tint = SettingsMuted
        )
    }
}
