package dev.kaizen.app.auth

import android.os.Build
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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import dev.kaizen.app.ui.shape.KaizenShapes
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import dev.kaizen.app.chat.KaizenOrb
import dev.kaizen.app.chat.MeshBackground
import dev.kaizen.app.net.DEFAULT_BASE_URL
import dev.kaizen.app.net.LoginResult
import dev.kaizen.app.net.SessionViewModel
import dev.kaizen.app.ui.effect.KaizenShadows
import dev.kaizen.app.ui.effect.kaizenShadow
import dev.kaizen.app.ui.theme.KaizenSemanticColors
import dev.kaizen.app.ui.theme.LocalKaizenAccent
import androidx.compose.ui.res.stringResource
import dev.kaizen.app.R
import kotlinx.coroutines.launch

/**
 * In-app sign-in (consumer "Sign in" pattern, not token copy-paste). The server-URL
 * field IS the "official / self-host address" — default points at the official
 * instance, edit it to authenticate against any self-host. On success the session
 * flips and the app routes into the chat.
 */
@Composable
fun LoginScreen(session: SessionViewModel, modifier: Modifier = Modifier) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val scope = rememberCoroutineScope()
    val ctx = androidx.compose.ui.platform.LocalContext.current

    var baseUrl by remember { mutableStateOf(DEFAULT_BASE_URL) }
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var loading by remember { mutableStateOf(false) }
    var error by remember { mutableStateOf<String?>(null) }

    val deviceName = remember { Build.MODEL ?: "Android" }
    val canSubmit = baseUrl.isNotBlank() && email.isNotBlank() && password.isNotBlank() && !loading

    fun submit() {
        if (!canSubmit) return
        loading = true
        error = null
        scope.launch {
            when (val result = session.login(baseUrl, email, password, deviceName)) {
                is LoginResult.Success -> Unit // session.config flips → MainActivity routes to chat
                LoginResult.InvalidCredentials -> error = ctx.getString(R.string.login_error_credentials)
                LoginResult.RateLimited -> error = ctx.getString(R.string.login_error_rate_limited)
                is LoginResult.Error -> error = ctx.getString(R.string.login_error_connection)
            }
            loading = false
        }
    }

    MeshBackground {
        Column(
            modifier = modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .imePadding()
                .padding(horizontal = 28.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
        ) {
            Spacer(Modifier.size(64.dp))
            KaizenOrb(96.dp)
            Spacer(Modifier.size(24.dp))
            Text(stringResource(R.string.login_welcome), color = cs.onBackground, fontSize = 30.sp, fontWeight = FontWeight.Bold)
            Spacer(Modifier.size(6.dp))
            Text(
                stringResource(R.string.login_subtitle),
                color = cs.onSurfaceVariant.copy(alpha = 0.8f),
                fontSize = 14.sp,
            )

            Spacer(Modifier.size(36.dp))

            GlassField(
                value = baseUrl,
                onValueChange = { baseUrl = it; error = null },
                placeholder = stringResource(R.string.login_url_placeholder),
                keyboardType = KeyboardType.Uri,
                imeAction = ImeAction.Next,
            )
            Spacer(Modifier.size(12.dp))
            GlassField(
                value = email,
                onValueChange = { email = it; error = null },
                placeholder = stringResource(R.string.login_email_placeholder),
                keyboardType = KeyboardType.Email,
                imeAction = ImeAction.Next,
            )
            Spacer(Modifier.size(12.dp))
            GlassField(
                value = password,
                onValueChange = { password = it; error = null },
                placeholder = stringResource(R.string.login_password_placeholder),
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Done,
                password = true,
                onImeDone = { submit() },
            )

            if (error != null) {
                Spacer(Modifier.size(14.dp))
                Text(error!!, color = KaizenSemanticColors.error, fontSize = 13.sp)
            }

            Spacer(Modifier.size(24.dp))
            SignInButton(enabled = canSubmit, loading = loading, onClick = { submit() })
            Spacer(Modifier.size(80.dp))
        }
    }
}

@Composable
private fun GlassField(
    value: String,
    onValueChange: (String) -> Unit,
    placeholder: String,
    keyboardType: KeyboardType,
    imeAction: ImeAction,
    password: Boolean = false,
    onImeDone: () -> Unit = {},
) {
    val cs = MaterialTheme.colorScheme
    val isDark = isSystemInDarkTheme()
    val accent = LocalKaizenAccent.current

    val glassBg = if (isDark) {
        Brush.verticalGradient(listOf(Color(0xFF1E293B).copy(alpha = 0.72f), Color(0xFF0F172A).copy(alpha = 0.85f)))
    } else {
        Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.90f), Color(0xFFEEF2F6).copy(alpha = 0.80f)))
    }
    val glassBorder = if (isDark) {
        Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.18f), Color.White.copy(alpha = 0.04f)))
    } else {
        Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.60f), Color.Black.copy(alpha = 0.06f)))
    }

    Box(
        Modifier
            .fillMaxWidth()
            .widthIn(max = 420.dp)
            .kaizenShadow(stack = KaizenShadows.level1, cornerRadius = 20.dp)
            .clip(KaizenShapes.lg)
            .background(glassBg)
            .border(1.2.dp, glassBorder, KaizenShapes.lg)
            .heightIn(min = 54.dp)
            .padding(horizontal = 18.dp, vertical = 16.dp),
        contentAlignment = Alignment.CenterStart,
    ) {
        if (value.isEmpty()) {
            Text(placeholder, color = cs.onSurfaceVariant.copy(alpha = 0.7f), fontSize = 16.sp)
        }
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            textStyle = TextStyle(color = cs.onBackground, fontSize = 16.sp),
            cursorBrush = SolidColor(accent.primary),
            singleLine = true,
            visualTransformation = if (password) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,
            keyboardOptions = KeyboardOptions(keyboardType = keyboardType, imeAction = imeAction),
            keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onImeDone() }),
            modifier = Modifier.fillMaxWidth(),
        )
    }
}

@Composable
private fun SignInButton(enabled: Boolean, loading: Boolean, onClick: () -> Unit) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val fill = if (enabled || loading) {
        Modifier.background(Brush.linearGradient(listOf(accent.primary, accent.primaryDeep)))
    } else {
        Modifier.background(cs.surface)
    }
    Box(
        Modifier
            .fillMaxWidth()
            .widthIn(max = 420.dp)
            .heightIn(min = 54.dp)
            .kaizenShadow(stack = KaizenShadows.level2, cornerRadius = 20.dp)
            .clip(KaizenShapes.lg)
            .then(fill)
            .clickable(enabled = enabled, onClick = onClick)
            .padding(vertical = 16.dp),
        contentAlignment = Alignment.Center,
    ) {
        if (loading) {
            CircularProgressIndicator(color = accent.onPrimary, strokeWidth = 2.4.dp, modifier = Modifier.size(22.dp))
        } else {
            Text(
                stringResource(R.string.login_submit),
                color = if (enabled) accent.onPrimary else cs.onSurfaceVariant,
                fontSize = 16.sp,
                fontWeight = FontWeight.SemiBold,
            )
        }
    }
}
