package id.iiyh.inatrading.core.ui.components

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
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.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusState
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.InaTradingTheme
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest
import id.iiyh.inatrading.core.ui.theme.InaShape

private val FieldShape = RoundedCornerShape(InaShape.md)

/**
 * Input field sesuai design spec:
 * - Normal state: background SurfaceContainerLow, no border
 * - Focus state: background SurfaceContainerLowest + "ghost border" primary @ 40% opacity
 * - Error state: ghost border ErrorRed @ 60% opacity
 */
@Composable
fun InaTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    label: String = "",
    placeholder: String = "",
    isPassword: Boolean = false,
    isError: Boolean = false,
    errorMessage: String = "",
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    onFocusChanged: ((FocusState) -> Unit)? = null,
) {
    var isFocused by remember { mutableStateOf(false) }

    val backgroundColor by animateColorAsState(
        targetValue = if (isFocused) SurfaceContainerLowest else SurfaceContainerLow,
        animationSpec = tween(150),
        label = "fieldBg",
    )

    val borderColor = when {
        isError  -> Color(0xFFBA1A1A).copy(alpha = 0.6f)
        isFocused -> BrandRed.copy(alpha = 0.4f)
        else      -> Color.Transparent
    }

    Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
        if (label.isNotEmpty()) {
            Text(
                text = label,
                style = MaterialTheme.typography.labelMedium,
                color = if (isError) Color(0xFFBA1A1A) else OnSurfaceVariant,
            )
        }

        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            textStyle = MaterialTheme.typography.bodyLarge.copy(color = OnSurface),
            cursorBrush = SolidColor(BrandRed),
            visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None,
            keyboardOptions = keyboardOptions,
            keyboardActions = keyboardActions,
            singleLine = true,
            modifier = Modifier
                .fillMaxWidth()
                .onFocusChanged {
                    isFocused = it.isFocused
                    onFocusChanged?.invoke(it)
                }
                .background(backgroundColor, FieldShape)
                .border(width = 1.dp, color = borderColor, shape = FieldShape)
                .padding(horizontal = 16.dp, vertical = 14.dp),
            decorationBox = { innerTextField ->
                Box(modifier = Modifier.fillMaxWidth()) {
                    if (leadingIcon != null) {
                        Box(
                            modifier = Modifier
                                .size(20.dp)
                                .align(androidx.compose.ui.Alignment.CenterStart)
                        ) {
                            leadingIcon()
                        }
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(
                                start = if (leadingIcon != null) 32.dp else 0.dp,
                                end = if (trailingIcon != null) 32.dp else 0.dp,
                            )
                    ) {
                        if (value.isEmpty() && placeholder.isNotEmpty()) {
                            Text(
                                text = placeholder,
                                style = MaterialTheme.typography.bodyLarge,
                                color = OnSurfaceVariant.copy(alpha = 0.6f),
                            )
                        }
                        innerTextField()
                    }

                    if (trailingIcon != null) {
                        Box(
                            modifier = Modifier
                                .size(20.dp)
                                .align(androidx.compose.ui.Alignment.CenterEnd)
                        ) {
                            trailingIcon()
                        }
                    }
                }
            },
        )

        if (isError && errorMessage.isNotEmpty()) {
            Text(
                text = errorMessage,
                style = MaterialTheme.typography.bodySmall,
                color = Color(0xFFBA1A1A),
            )
        }
    }
}

// ─── Preview ──────────────────────────────────────────────────────────────────
@Preview(showBackground = true, backgroundColor = 0xFFF8FAFB)
@Composable
private fun InaTextFieldPreview() {
    InaTradingTheme {
        var text by remember { mutableStateOf("") }
        var pass by remember { mutableStateOf("") }

        Column(
            modifier = Modifier.padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            InaTextField(
                value = text,
                onValueChange = { text = it },
                label = "Email",
                placeholder = "contoh@email.com",
            )
            InaTextField(
                value = pass,
                onValueChange = { pass = it },
                label = "Password",
                placeholder = "Minimal 8 karakter",
                isPassword = true,
            )
            InaTextField(
                value = "email-salah",
                onValueChange = {},
                label = "Email",
                isError = true,
                errorMessage = "Format email tidak valid",
            )
        }
    }
}
