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.PaddingValues
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.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.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
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.data.api.ErrorCode
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.CaptchaService
import com.aiosman.ravenow.data.CaptchaServiceImpl
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.api.CaptchaInfo
import com.aiosman.ravenow.data.api.CaptchaResponseBody
import com.aiosman.ravenow.data.api.DotPosition
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.comment.NoticeScreenHeader
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.composables.ClickCaptchaDialog
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.GoogleLogin
import com.aiosman.ravenow.utils.PasswordValidator
import kotlinx.coroutines.launch


@Composable
fun UserAuthScreen() {
    val AppColors = LocalAppTheme.current
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var rememberMe by remember { mutableStateOf(false) }
    val accountService: AccountService = AccountServiceImpl()
    val captchaService: CaptchaService = CaptchaServiceImpl()
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    val context = LocalContext.current
    var emailError by remember { mutableStateOf<String?>(null) }
    var passwordError by remember { mutableStateOf<String?>(null) }
    var captchaInfo by remember { mutableStateOf<CaptchaInfo?>(null) }
    fun validateForm(): Boolean {
        emailError =
            if (email.isEmpty()) context.getString(R.string.text_error_email_required) else null
        
        // 使用通用密码校验器
        val passwordValidation = PasswordValidator.validateCurrentPassword(password, context)
        passwordError = if (!passwordValidation.isValid) passwordValidation.errorMessage else null
        
        return emailError == null && passwordError == null
    }

    var captchaData by remember { mutableStateOf<CaptchaResponseBody?>(null) }
    fun loadLoginCaptcha() {
        scope.launch {
            try {
                captchaData = captchaService.generateLoginCaptcha(email)
                captchaData?.let {
                    captchaInfo = CaptchaInfo(
                        id = it.id,
                        dot = emptyList()
                    )
                }

            } catch (e: ServiceException) {
                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun onLogin(captchaInfo: CaptchaInfo? = null) {
        if (!validateForm()) {
            return
        }
        scope.launch {
            try {
                // 检查是否需要验证码
                if (captchaInfo == null && captchaService.checkLoginCaptcha(email)) {
                    loadLoginCaptcha()
                    return@launch
                }
                // 获取用户凭证
                val authResp = accountService.loginUserWithPassword(email, password, captchaInfo)
                if (authResp.token != null) {
                    AppStore.apply {
                        token = authResp.token
                        this.rememberMe = rememberMe
                        isGuest = false  // 清除游客状态
                        saveData()
                    }
                    AppState.initWithAccount(scope, context)
                    navController.navigate(NavigationRoute.Index.route) {
                        popUpTo(NavigationRoute.Login.route) { inclusive = true }
                    }
                }
            } catch (e: ServiceException) {
                // handle error
                when (e.code) {
                    12005 -> {
                        emailError = context.getString(R.string.error_invalidate_username_password)
                        passwordError = context.getString(R.string.error_invalidate_username_password)
                    }
                    ErrorCode.InvalidateCaptcha.code -> {
                        loadLoginCaptcha()
                        Toast.makeText(
                            context,
                            context.getString(R.string.incorrect_captcha_please_try_again),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                    else -> {
                        Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
            } finally {
                captchaData = null
            }
        }

    }


    fun googleLogin() {
        val clientId = AppState.googleClientId
        if (clientId == null) {
            Toast.makeText(context, "Google login not supported", Toast.LENGTH_SHORT).show()
            return
        }
        scope.launch {
            try {
                GoogleLogin(context,clientId) {
                    scope.launch {
                        try {
                            val authResp = accountService.loginUserWithGoogle(it)
                            if (authResp.token != null) {
                                AppStore.apply {
                                    token = authResp.token
                                    this.rememberMe = rememberMe
                                    isGuest = false  // 清除游客状态
                                    saveData()
                                }
                                navController.navigate(NavigationRoute.Index.route) {
                                    popUpTo(NavigationRoute.Login.route) { inclusive = true }
                                }
                            }
                        } catch (e: ServiceException) {
                            // handle error
                            e.printStackTrace()
                            Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            } catch (e: Exception) {
                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
            }
        }

    }
    captchaData?.let {
        ClickCaptchaDialog(
            onDismissRequest = {
                captchaData = null
            },
            captchaData = it,
            onLoadCaptcha = {
                loadLoginCaptcha()
            },
            onPositionClicked = { offset ->
                captchaInfo?.let { info ->
                    val dots = info.dot.toMutableList()
                    val lastDotIndex = dots.size - 1
                    dots += DotPosition(
                        index = lastDotIndex + 1,
                        x = offset.x.toInt(),
                        y = offset.y.toInt()
                    )
                    captchaInfo = info.copy(dot = dots)
                    // 检查是否完成
                    if (dots.size == it.count) {
                        onLogin(captchaInfo)
                    }
                }
            },
        )
    }
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp, start = 16.dp, end = 16.dp)
        ) {
            NoticeScreenHeader(stringResource(R.string.login_upper), moreIcon = false)
        }
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)

                .padding(horizontal = 24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,

        ) {
            StatusBarSpacer()
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth(),
                text = email,
                onValueChange = {
                    email = it
                },
                hint = stringResource(R.string.text_hint_email),
                error = emailError
            )
            Spacer(modifier = Modifier.padding(4.dp))
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth(),
                text = password,
                onValueChange = {
                    password = it
                },
                password = true,
                hint = stringResource(R.string.text_hint_password),
                error = passwordError
            )
            Spacer(modifier = Modifier.height(32.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                com.aiosman.ravenow.ui.composables.Checkbox(
                    checked = rememberMe,
                    onCheckedChange = {
                        rememberMe = it
                    },
                    size = 18
                )
                Text(
                    stringResource(R.string.remember_me),
                    modifier = Modifier.padding(start = 8.dp),
                    fontSize = 12.sp,
                    style = TextStyle(
                        fontWeight = FontWeight.W500
                    ),
                    color = AppColors.text
                )
                Spacer(modifier = Modifier.weight(1f))
                Text(
                    stringResource(R.string.forgot_password),
                    fontSize = 12.sp,
                    modifier = Modifier.noRippleClickable {
                        navController.navigate(NavigationRoute.ResetPassword.route)
                    },
                    style = TextStyle(
                        fontWeight = FontWeight.W500
                    ),
                    color = AppColors.text
                )

            }
            Spacer(modifier = Modifier.height(46.dp))
            ActionButton(
                modifier = Modifier.fillMaxWidth(),
                text = stringResource(R.string.lets_ride_upper),
                backgroundColor = AppColors.main,
                color = AppColors.mainText,
            ) {
                onLogin()
            }
            if (AppState.enableGoogleLogin) {
                Spacer(modifier = Modifier.height(16.dp))
                Text(stringResource(R.string.or_login_with), color = AppColors.secondaryText)
                Spacer(modifier = Modifier.height(16.dp))
                ActionButton(
                    modifier = Modifier.fillMaxWidth(),
                    text = stringResource(R.string.sign_in_with_google),
                    color = AppColors.text,
                    leading = {
                        Image(
                            painter = painterResource(id = R.drawable.rider_pro_google),
                            contentDescription = "Google",
                            modifier = Modifier.size(36.dp)
                        )
                    },
                    expandText = true,
                    contentPadding = PaddingValues(vertical = 8.dp, horizontal = 8.dp)
                ) {
                    googleLogin()
                }
            }

        }

    }


}

