package com.aiosman.ravenow.ui.login

import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.width
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.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.data.api.ErrorCode
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.api.getErrorMessageCode
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.composables.CheckboxWithLabel
import com.aiosman.ravenow.ui.composables.PolicyCheckbox
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.TextInputField
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.PasswordValidator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

private val LightGrayBackground = Color(red = 250f / 255f, green = 249f / 255f, blue = 251f / 255f)
private val IconGray = Color(red = 151f / 255f, green = 148f / 255f, blue = 153f / 255f)
private val PurpleButton = Color(0xFF7C45ED)

@Composable
fun EmailSignupScreen() {
    val appColor = LocalAppTheme.current
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var rememberMe by remember { mutableStateOf(false) }
    var acceptTerms by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    val context = LocalContext.current
    val accountService: AccountService = AccountServiceImpl()
    var emailError by remember { mutableStateOf<String?>(null) }
    var passwordError by remember { mutableStateOf<String?>(null) }
    var confirmPasswordError by remember { mutableStateOf<String?>(null) }
    var termsError by remember { mutableStateOf<Boolean>(false) }
    fun validateForm(): Boolean {
        emailError = when {
            // 非空
            email.isEmpty() -> context.getString(R.string.text_error_email_required)
            // 邮箱格式
            !android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                .matches() -> context.getString(R.string.text_error_email_format_1)

            else -> null
        }
        // 使用通用密码校验器
        val passwordValidation = PasswordValidator.validatePassword(password, context)
        passwordError = if (!passwordValidation.isValid) passwordValidation.errorMessage else null
        
        // 使用通用密码确认校验器
        val confirmPasswordValidation = PasswordValidator.validatePasswordConfirmation(password, confirmPassword, context)
        confirmPasswordError = if (!confirmPasswordValidation.isValid) confirmPasswordValidation.errorMessage else null
        if (!acceptTerms) {
            scope.launch(Dispatchers.Main) {
                Toast.makeText(
                    context,
                    context.getString(R.string.error_not_accept_term),
                    Toast.LENGTH_SHORT
                ).show()
            }
            termsError = true
            return false
        }
        termsError = false

        return emailError == null && passwordError == null && confirmPasswordError == null
    }

    suspend fun registerUser() {
        if (!validateForm()) return
        // 注册
        try {
            accountService.registerUserWithPassword(email, password)
        } catch (e: ServiceException) {
            scope.launch(Dispatchers.Main) {
                if (e.code == ErrorCode.USER_EXIST.code) {
                    emailError = context.getString(R.string.error_10001_user_exist)
                    return@launch
                }
                Toast.makeText(context, context.getErrorMessageCode(e.code), Toast.LENGTH_SHORT)
                    .show()
            }
            return
        } catch (e: Exception) {
            scope.launch(Dispatchers.Main) {
                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
            }
            return
        }
        // 获取 token
        val authResp = accountService.loginUserWithPassword(email, password)
        if (authResp.token != null) {
            scope.launch(Dispatchers.Main) {
                Toast.makeText(context, "Successfully registered", Toast.LENGTH_SHORT).show()
            }
        }
        AppStore.apply {
            token = authResp.token
            this.rememberMe = rememberMe
            isGuest = false  // 清除游客状态
            saveData()
        }
        // 获取token 信息
        try {
            AppState.initWithAccount(scope, context)
        } catch (e: ServiceException) {
            scope.launch(Dispatchers.Main) {
                Toast.makeText(context, "Failed to get account", Toast.LENGTH_SHORT).show()
            }
        }
        scope.launch(Dispatchers.Main) {
            navController.navigate(NavigationRoute.Index.route) {
                popUpTo(NavigationRoute.Login.route) { inclusive = true }
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(appColor.background)
    ) {
        StatusBarSpacer()
        // 顶部导航栏：返回箭头 + "注册"标题，左对齐
        // 根据暗色模式适配颜色
        val isDarkMode = AppState.darkMode
        val textColor = if (isDarkMode) {
            Color.White
        } else {
            Color.Black
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 15.dp, start = 16.dp, bottom = 15.dp, end = 16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = R.drawable.rider_pro_back_icon),
                contentDescription = "Back",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        navController.navigateUp()
                    },
                colorFilter = ColorFilter.tint(textColor)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = stringResource(R.string.sign_up_upper),
                fontSize = 20.sp,
                fontWeight = FontWeight.W600,
                color = textColor
            )
        }
        
        // 输入区域
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .padding(horizontal = 0.dp)
        ) {
            Spacer(modifier = Modifier.height(16.dp))
            
            // 暗色模式下的输入框颜色配置
            val isDarkMode = AppState.darkMode
            val inputBackgroundColor = if (isDarkMode) {
                Color(0xFF1C1C1C) // 暗色模式下深灰色背景
            } else {
                null // 亮色模式下使用默认背景
            }
            val textColor = if (isDarkMode) {
                Color(0xFFFFFFFF).copy(alpha = 0.7f) // 暗色模式下 label 和 hint 文本颜色
            } else {
                null // 使用默认颜色
            }
            
            // 邮箱输入框
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                text = email,
                onValueChange = {
                    email = it
                },
                label = stringResource(R.string.login_email_label),
                hint = stringResource(R.string.text_hint_email),
                error = emailError,
                leadingIcon = {
                    Image(
                        painter = painterResource(id = R.mipmap.icon_email_light),
                        contentDescription = "Email",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(IconGray)
                    )
                },
                customBackgroundColor = inputBackgroundColor,
                customHintColor = textColor,
                customLabelColor = textColor,
                customCornerRadius = 16f
            )
            
            // 密码输入框
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                text = password,
                onValueChange = {
                    password = it
                },
                password = true,
                label = stringResource(R.string.text_hint_password).replace("输入", ""),
                hint = stringResource(R.string.text_hint_password),
                error = passwordError,
                leadingIcon = {
                    Image(
                        painter = painterResource(id = R.mipmap.icon_lock_light),
                        contentDescription = "Lock",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(IconGray)
                    )
                },
                customBackgroundColor = inputBackgroundColor,
                customHintColor = textColor,
                customLabelColor = textColor,
                customCornerRadius = 16f
            )
            
            // 确认密码输入框
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                text = confirmPassword,
                onValueChange = {
                    confirmPassword = it
                },
                password = true,
                label = stringResource(R.string.confirm_password_label),
                hint = stringResource(R.string.text_hint_password),
                error = confirmPasswordError,
                leadingIcon = {
                    Image(
                        painter = painterResource(id = R.mipmap.icon_lock_light),
                        contentDescription = "Lock",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(IconGray)
                    )
                },
                customBackgroundColor = inputBackgroundColor,
                customHintColor = textColor,
                customLabelColor = textColor,
                customCornerRadius = 16f
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 功能选项区域
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                horizontalAlignment = Alignment.Start,
            ) {
                CheckboxWithLabel(
                    checked = rememberMe,
                    checkSize = 16,
                    fontSize = 12,
                    label = stringResource(R.string.remember_me),
                ) {
                    rememberMe = it
                }
                Spacer(modifier = Modifier.height(16.dp))
                PolicyCheckbox(
                    checked = acceptTerms,
                    error = termsError
                ) {
                    acceptTerms = it
                    // 当用户勾选时，立即清除错误状态
                    if (it) {
                        termsError = false
                    }
                }
            }

            Spacer(modifier = Modifier.height(76.dp))
            
            // 底部注册按钮
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp),
                contentAlignment = Alignment.Center
            ) {
                ActionButton(
                    modifier = Modifier.fillMaxWidth(),
                    text = stringResource(R.string.sign_up_upper),
                    backgroundColor = PurpleButton,
                    color = Color.White,
                    fontSize = 17.sp,
                    fontWeight = FontWeight.W600
                ) {
                    scope.launch(Dispatchers.IO) {
                        registerUser()
                    }
                }
            }
        }
    }

}