package com.aiosman.riderpro.ui.login

import android.widget.Toast
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.ExperimentalMaterial3Api
import androidx.compose.material3.LocalMinimumInteractiveComponentEnforcement
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
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.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.AppStore
import com.aiosman.riderpro.ErrorCode
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.Messaging
import com.aiosman.riderpro.R
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.ServiceException
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.getErrorMessageCode
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.comment.NoticeScreenHeader
import com.aiosman.riderpro.ui.composables.ActionButton
import com.aiosman.riderpro.ui.composables.Checkbox
import com.aiosman.riderpro.ui.composables.CheckboxWithLabel
import com.aiosman.riderpro.ui.composables.StatusBarMaskLayout
import com.aiosman.riderpro.ui.composables.StatusBarSpacer
import com.aiosman.riderpro.ui.composables.TextInputField
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun EmailSignupScreen() {
    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) }
    var acceptPromotions 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) }
    var promotionsError 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)

            else -> null
        }
        passwordError = when {
            // 非空
            password.isEmpty() -> context.getString(R.string.text_error_password_required)
            // 包含大写字母
            !password.matches(Regex(".*[A-Z].*")) -> context.getString(R.string.text_error_password_format)
            // 至少8位
            password.length < 8 -> context.getString(R.string.text_error_password_format)
            // 至少一个数字
            !password.matches(Regex(".*\\d.*")) -> context.getString(R.string.text_error_password_format)
            // 包含小写字母
            !password.matches(Regex(".*[a-z].*")) -> context.getString(R.string.text_error_password_format)
            else -> null
        }
        confirmPasswordError = when {
            // 非空
            confirmPassword.isEmpty() -> context.getString(R.string.text_error_confirm_password_required)
            // 与密码一致
            confirmPassword != password -> context.getString(R.string.text_error_confirm_password_mismatch)
            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
        } else {
            termsError = false
        }
        if (!acceptPromotions) {
            scope.launch(Dispatchers.Main) {
                Toast.makeText(
                    context,
                    context.getString(R.string.error_not_accept_recive_notice),
                    Toast.LENGTH_SHORT
                ).show()
            }
            promotionsError = true
            return false
        } else {
            promotionsError = 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
            saveData()
        }
        // 获取token 信息
        try {
            val resp = accountService.getMyAccount()
            AppState.UserId = resp.id
            Messaging.InitFCM(scope)
        } 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(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp, start = 16.dp, end = 16.dp)
        ) {
            NoticeScreenHeader(stringResource(R.string.sign_in_upper), moreIcon = false)
        }
        Spacer(modifier = Modifier.padding(32.dp))
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .padding(horizontal = 24.dp)
        ) {
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth(),
                text = email,
                onValueChange = {
                    email = it
                },
                label = stringResource(R.string.login_email_label),
                hint = stringResource(R.string.text_hint_email),
                error = emailError
            )
            Spacer(modifier = Modifier.padding(8.dp))
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth(),
                text = password,
                onValueChange = {
                    password = it
                },
                password = true,
                label = stringResource(R.string.login_password_label),
                hint = stringResource(R.string.text_hint_password),
                error = passwordError
            )
            Spacer(modifier = Modifier.padding(8.dp))
            TextInputField(
                modifier = Modifier
                    .fillMaxWidth(),
                text = confirmPassword,
                onValueChange = {
                    confirmPassword = it
                },
                password = true,
                label = stringResource(R.string.login_confirm_password_label),
                hint = stringResource(R.string.text_hint_confirm_password),
                error = confirmPasswordError
            )
            Spacer(modifier = Modifier.height(16.dp))
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.Start,
            ) {
                CheckboxWithLabel(
                    checked = rememberMe,
                    checkSize = 16,
                    fontSize = 12,
                    label = stringResource(R.string.remember_me),
                ) {
                    rememberMe = it
                }
                Spacer(modifier = Modifier.height(16.dp))
                CheckboxWithLabel(
                    checked = acceptTerms,
                    checkSize = 16,
                    fontSize = 12,
                    label = stringResource(R.string.agree_terms_of_service),
                    error = termsError
                ) {
                    acceptTerms = it
                }
                Spacer(modifier = Modifier.height(16.dp))
                CheckboxWithLabel(
                    checked = acceptPromotions,
                    checkSize = 16,
                    fontSize = 12,
                    label = stringResource(R.string.agree_promotion),
                    error = promotionsError
                ) {
                    acceptPromotions = it
                }
            }

            Spacer(modifier = Modifier.height(64.dp))
            ActionButton(
                modifier = Modifier
                    .width(345.dp)
                    .height(48.dp),
                text = stringResource(R.string.lets_ride_upper),
                backgroundImage = R.mipmap.rider_pro_signup_red_bg
            ) {
                scope.launch(Dispatchers.IO) {
                    registerUser()
                }
            }
        }

    }

}