package dev.kaizen.app.auth

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.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.stringResource
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 androidx.compose.ui.window.Dialog
import dev.kaizen.app.R
import dev.kaizen.app.ui.effect.GlassSurface
import dev.kaizen.app.ui.effect.GlassTiers
import dev.kaizen.app.ui.shape.KaizenShapes
import dev.kaizen.app.ui.theme.KaizenSemanticColors
import dev.kaizen.app.ui.theme.LocalKaizenAccent

@Composable
fun PasswordUnlockDialog(
    onSubmit: (password: String) -> Unit,
    onDismiss: () -> Unit,
    error: String? = null,
) {
    var password by remember { mutableStateOf("") }
    val focusRequester = remember { FocusRequester() }

    LaunchedEffect(Unit) { focusRequester.requestFocus() }

    val isDark = isSystemInDarkTheme()

    Dialog(onDismissRequest = onDismiss) {
        GlassSurface(
            shape = KaizenShapes.xl,
            tintAlpha = GlassTiers.card(isDark),
        ) {
            Column(Modifier.padding(24.dp)) {
                Text(
                    stringResource(R.string.unlock_password_title),
                    color = MaterialTheme.colorScheme.onBackground,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.SemiBold,
                )
                Spacer(Modifier.size(6.dp))
                Text(
                    stringResource(R.string.unlock_password_subtitle),
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                    fontSize = 13.sp,
                )
                Spacer(Modifier.size(20.dp))

                PasswordField(
                    value = password,
                    onValueChange = { password = it },
                    onImeDone = { if (password.isNotBlank()) onSubmit(password) },
                    modifier = Modifier.focusRequester(focusRequester),
                )

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

                Spacer(Modifier.size(20.dp))

                Row(Modifier.fillMaxWidth()) {
                    DialogButton(
                        label = stringResource(R.string.unlock_password_cancel),
                        enabled = true,
                        primary = false,
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f),
                    )
                    Spacer(Modifier.width(10.dp))
                    DialogButton(
                        label = stringResource(R.string.unlock_password_submit),
                        enabled = password.isNotBlank(),
                        primary = true,
                        onClick = { onSubmit(password) },
                        modifier = Modifier.weight(1f),
                    )
                }
            }
        }
    }
}

@Composable
private fun PasswordField(
    value: String,
    onValueChange: (String) -> Unit,
    onImeDone: () -> Unit,
    modifier: Modifier = Modifier,
) {
    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()
            .shadow(elevation = 4.dp, shape = KaizenShapes.md, clip = false)
            .clip(KaizenShapes.md)
            .background(glassBg)
            .border(1.dp, glassBorder, KaizenShapes.md)
            .heightIn(min = 48.dp)
            .padding(horizontal = 16.dp, vertical = 14.dp),
        contentAlignment = Alignment.CenterStart,
    ) {
        if (value.isEmpty()) {
            Text(
                stringResource(R.string.unlock_password_placeholder),
                color = cs.onSurfaceVariant.copy(alpha = 0.5f),
                fontSize = 15.sp,
            )
        }
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            textStyle = TextStyle(color = cs.onBackground, fontSize = 15.sp),
            cursorBrush = SolidColor(accent.primary),
            singleLine = true,
            visualTransformation = PasswordVisualTransformation(),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
            keyboardActions = KeyboardActions(onDone = { onImeDone() }),
            modifier = modifier.fillMaxWidth(),
        )
    }
}

@Composable
private fun DialogButton(
    label: String,
    enabled: Boolean,
    primary: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val fill = if (primary && enabled) {
        Modifier.background(Brush.linearGradient(listOf(accent.primary, accent.primaryDeep)))
    } else {
        Modifier.background(cs.surface.copy(alpha = 0.6f))
    }

    Box(
        modifier
            .heightIn(min = 44.dp)
            .shadow(elevation = if (primary) 4.dp else 2.dp, shape = KaizenShapes.md, clip = false)
            .clip(KaizenShapes.md)
            .then(fill)
            .clickable(enabled = enabled, onClick = onClick)
            .padding(vertical = 12.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            label,
            color = if (primary && enabled) accent.onPrimary else cs.onSurfaceVariant,
            fontSize = 14.sp,
            fontWeight = if (primary) FontWeight.SemiBold else FontWeight.Normal,
        )
    }
}
