package dev.kaizen.app.settings

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import dev.kaizen.app.ui.effect.GlassSurface
import dev.kaizen.app.ui.effect.GlassTiers
import dev.kaizen.app.ui.effect.KaizenShadows
import dev.kaizen.app.ui.shape.KaizenShapes
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import dev.kaizen.app.R
import dev.kaizen.app.ui.theme.themes.KaizenThemeId
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import dev.kaizen.app.chat.MeshBackground
import dev.kaizen.app.ui.icon.KaizenIcons

/**
 * Premium, fully responsive, glassmorphic Settings Screen.
 * 
 * Includes the Oklab Theme Picker, Light/Dark/System appearance segmented pills, 
 * and user profile text fields, completely driven by our clean, decoupled SettingsViewModel.
 */
@Composable
fun SettingsScreen(
    viewModel: SettingsViewModel,
    config: dev.kaizen.app.net.ServerConfig? = null,
    onBack: () -> Unit,
    modifier: Modifier = Modifier
) {
    val cs = MaterialTheme.colorScheme
    val isDark = isSystemInDarkTheme()

    // Collect reactive state flows from the ViewModel (clean MVVM)
    val selectedTheme by viewModel.selectedTheme.collectAsState()
    val appearanceMode by viewModel.appearanceMode.collectAsState()
    val userName by viewModel.userName.collectAsState()
    val userEmail by viewModel.userEmail.collectAsState()
    val locale by viewModel.locale.collectAsState()

    MeshBackground {
        Column(
            modifier = modifier
                .fillMaxSize()
                .statusBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 20.dp, vertical = 12.dp)
        ) {
            
            // --- HEADER: Back Arrow Button & Title Sektion ---
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 24.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                GlassSurface(
                    shape = KaizenShapes.circle,
                    tintAlpha = GlassTiers.pill(isDark),
                    shadowStack = KaizenShadows.level2,
                    cornerRadius = 22.dp,
                    modifier = Modifier.size(44.dp).clickable { onBack() },
                ) {
                    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        Icon(KaizenIcons.ArrowLeft, stringResource(R.string.settings_back), tint = cs.onBackground, modifier = Modifier.size(20.dp))
                    }
                }
                
                Spacer(Modifier.width(16.dp))
                
                Text(stringResource(R.string.settings_title), color = cs.onBackground, fontSize = 24.sp, fontWeight = FontWeight.Bold)
            }

            Text(stringResource(R.string.settings_section_appearance), color = cs.onSurfaceVariant.copy(alpha = 0.6f), fontSize = 12.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 8.dp, bottom = 8.dp))

            SettingsCard(modifier = Modifier.padding(bottom = 24.dp)) {
                SettingsOptionRow(title = stringResource(R.string.settings_accent_title), description = stringResource(R.string.settings_accent_desc), icon = KaizenIcons.Palette) {
                    Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
                        KaizenThemeId.entries.forEach { theme ->
                            ThemeOptionPill(themeId = theme, selected = selectedTheme == theme, onClick = { viewModel.selectTheme(theme) })
                        }
                    }
                }
                Spacer(Modifier.height(12.dp))
                SettingsOptionRow(title = stringResource(R.string.settings_appearance_title), description = stringResource(R.string.settings_appearance_desc), icon = KaizenIcons.Settings) {
                    Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
                        AppAppearance.entries.forEach { mode ->
                            val label = when (mode) {
                                AppAppearance.Light -> stringResource(R.string.settings_appearance_light)
                                AppAppearance.Dark -> stringResource(R.string.settings_appearance_dark)
                                AppAppearance.System -> stringResource(R.string.settings_appearance_system)
                            }
                            AppearanceTogglePill(selected = appearanceMode == mode, label = label, onClick = { viewModel.selectAppearance(mode) })
                        }
                    }
                }
                Spacer(Modifier.height(12.dp))
                SettingsOptionRow(title = stringResource(R.string.settings_language_title), description = stringResource(R.string.settings_language_desc), icon = KaizenIcons.Globe) {
                    Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
                        listOf("system" to R.string.settings_language_system, "de" to R.string.settings_language_de, "en" to R.string.settings_language_en).forEach { (code, labelRes) ->
                            val ctx = LocalContext.current
                            AppearanceTogglePill(selected = locale == code, label = stringResource(labelRes), onClick = { viewModel.selectLocale(code, ctx as? android.app.Activity) })
                        }
                    }
                }
            }

            Text(stringResource(R.string.settings_section_profile), color = cs.onSurfaceVariant.copy(alpha = 0.6f), fontSize = 12.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 8.dp, bottom = 8.dp))

            SettingsCard(modifier = Modifier.padding(bottom = 24.dp)) {
                SettingsOptionRow(title = stringResource(R.string.settings_name_title), description = stringResource(R.string.settings_name_desc), icon = KaizenIcons.User) {
                    SettingsInputCapsule(value = userName, onValueChange = { viewModel.updateUserName(it) })
                }
                Spacer(Modifier.height(12.dp))
                SettingsOptionRow(title = stringResource(R.string.settings_email_title), description = userEmail, icon = KaizenIcons.Settings)
            }

            Text(stringResource(R.string.settings_section_ai), color = cs.onSurfaceVariant.copy(alpha = 0.6f), fontSize = 12.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 8.dp, bottom = 8.dp))

            SettingsCard(modifier = Modifier.padding(bottom = 24.dp)) {
                SettingsOptionRow(title = stringResource(R.string.settings_ai_title), description = "", icon = KaizenIcons.Sparkles)
            }

            SecuritySection(viewModel = viewModel, config = config)
        }
    }
}
