package com.aiosman.ravenow.ui.composables

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.height
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.KeyboardOptions
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.modifiers.noRippleClickable

private val LabelTextColor = Color(red = 60f / 255f, green = 60f / 255f, blue = 67f / 255f, alpha = 0.6f)
private val HintTextColor = Color(red = 60f / 255f, green = 60f / 255f, blue = 67f / 255f, alpha = 0.3f)
private val PasswordIconColor = Color(red = 17f / 255f, green = 12f / 255f, blue = 19f / 255f)

@Composable
fun TextInputField(
    modifier: Modifier = Modifier,
    text: String,
    onValueChange: (String) -> Unit,
    password: Boolean = false,
    label: String? = null,
    hint: String? = null,
    error: String? = null,
    enabled: Boolean = true,
    leadingIcon: @Composable (() -> Unit)? = null,
    customBackgroundColor: Color? = null,
    customHintColor: Color? = null,
    customLabelColor: Color? = null,
    customCornerRadius: Float = 24f
) {
    val AppColors = LocalAppTheme.current
    var showPassword by remember { mutableStateOf(!password) }
    var isFocused by remember { mutableStateOf(false) }
    val backgroundColor = customBackgroundColor ?: AppColors.inputBackground
    val hintColor = customHintColor ?: HintTextColor
    val labelColor = customLabelColor ?: LabelTextColor
    Column(modifier = modifier) {
        label?.let {
            Text(
                text = it,
                color = labelColor,
                fontSize = 13.sp,
                modifier = Modifier.padding(start = 8.dp, top = 8.dp, bottom = 8.dp)
            )
        }
        Box(
            contentAlignment = Alignment.CenterStart,
            modifier = Modifier
                .clip(RoundedCornerShape(customCornerRadius.dp))
                .background(backgroundColor)
                .border(
                    width = 2.dp,
                    color = if (error == null) Color.Transparent  else AppColors.error,
                    shape = RoundedCornerShape(customCornerRadius.dp)
                )
                .padding(horizontal = 16.dp, vertical = 16.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ){
                leadingIcon?.let {
                    Box(modifier = Modifier.size(24.dp)) {
                        it()
                    }
                    Spacer(modifier = Modifier.size(12.dp))
                }
                Box(modifier = Modifier.weight(1f)) {
                    BasicTextField(
                        value = text,
                        onValueChange = onValueChange,
                        modifier = Modifier
                            .fillMaxWidth()
                            .onFocusChanged { focusState ->
                                isFocused = focusState.isFocused
                            },
                        textStyle = TextStyle(
                            fontSize = 16.sp,
                            fontWeight = FontWeight.W400,
                            color = AppColors.text
                        ),
                        keyboardOptions = KeyboardOptions(
                            keyboardType = if (password) KeyboardType.Password else KeyboardType.Email
                        ),
                        visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(),
                        singleLine = true,
                        enabled = enabled,
                        cursorBrush = SolidColor(AppColors.text),
                    )
                    if (text.isEmpty() && hint != null) {
                        Text(
                            text = hint,
                            color = hintColor,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.W400
                        )
                    }
                }
                if (password) {
                    // 暗色模式下图标为白色，否则使用默认颜色
                    val iconColor = if (AppState.darkMode) {
                        Color.White
                    } else {
                        PasswordIconColor
                    }
                    Image(
                        painter = painterResource(
                            id = if (showPassword) {
                                R.drawable.rider_pro_eye
                            } else {
                                R.mipmap.icon_eyes_closed_light
                            }
                        ),
                        contentDescription = "Password",
                        modifier = Modifier
                            .size(24.dp)
                            .noRippleClickable {
                                showPassword = !showPassword
                            },
                        colorFilter = ColorFilter.tint(iconColor)
                    )
                }
            }
        }
        Spacer(modifier = Modifier.height(8.dp))
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AnimatedVisibility(
                visible = error != null,
                enter = fadeIn(),
                exit = fadeOut()
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Image(
                        painter = painterResource(id = R.mipmap.rider_pro_input_error),
                        contentDescription = "Error",
                        modifier = Modifier.size(8.dp)
                    )
                    Spacer(modifier = Modifier.size(4.dp))
                    AnimatedContent(targetState = error) { targetError ->
                        Text(targetError ?: "", color = AppColors.error, fontSize = 12.sp)
                    }
                }
            }
        }
    }
}