package com.example.what_the_fantasy.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
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.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
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 androidx.lifecycle.viewmodel.compose.viewModel
import com.example.what_the_fantasy.R
import com.example.what_the_fantasy.data.model.Image
import com.example.what_the_fantasy.ui.components.SpaceHeightComponent
import com.example.what_the_fantasy.ui.components.TitlePageComponent
import com.example.what_the_fantasy.ui.components.ErrorMessageProfileComponent
import com.example.what_the_fantasy.ui.components.VisibleIconPasswordComponent
import com.example.what_the_fantasy.ui.states.SignInUserState
import com.example.what_the_fantasy.ui.viewModels.SignInUserViewModel

@Composable
fun SignUpPage(navControllerLogin: () -> Unit, signInUserVM :SignInUserViewModel,signInState : SignInUserState) {


    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .verticalScroll(rememberScrollState()),
        contentAlignment = Alignment.Center
    ){
        Column(
            modifier = Modifier
                .fillMaxWidth(0.9f)
                .padding(20.dp)
                .clip(RoundedCornerShape(16.dp))
                .background(MaterialTheme.colorScheme.onPrimary)
                .padding(20.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            TitlePageComponent(R.string.titleSignUp,MaterialTheme.colorScheme.onBackground) // Page Title

            IdentifiantTextFieldSign(R.string.IdentifiantLogin,signInState.username){ // Username
                signInUserVM.setUsername(it)
            }

            EmailTextFieldSign(R.string.EmailSignUp, signInState.email){ // Email
                signInUserVM.setEmail(it)
            }
            PassWdTextFieldSign(R.string.PasswdLogin,signInState.password){ // Password
                signInUserVM.setPassword(it)
            }

            PassWdConfirmTextFieldSign(R.string.ConfirmPassWdSignUp,signInState.confirmPassword){ // confirm Password
                signInUserVM.setConfirmPassword(it)
            }

            SpaceHeightComponent(16)

            ConnexionButtonSign(R.string.ButtonSignUp,18, Color.White, Color.Black, signInState.username, signInState.email, signInState.password, signInState.confirmPassword, signInUserVM, navControllerLogin)
            SpaceHeightComponent(16)

            ReturnLogin(R.string.ButtonLogin,12, Color.White, navController = navControllerLogin)

        }
    }
}


@Composable
fun IdentifiantTextFieldSign(textIdentifiantResId : Int, identifiant: String, onValueChange: (String) -> Unit){
    val textIdentifiant = stringResource(id = textIdentifiantResId)

    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = identifiant,
            onValueChange = onValueChange,
            label = { Text(textIdentifiant) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp)
        )
    }
}

@Composable
fun EmailTextFieldSign(textIdentifiantResId: Int, email: String, onValueChange: (String) -> Unit){
    val textIdentifiant = stringResource(id = textIdentifiantResId)
    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = email,
            onValueChange = onValueChange,
            label = { Text(textIdentifiant) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
            shape = RoundedCornerShape(16.dp)
        )
    }
}

@Composable
fun PassWdTextFieldSign(textpasswdResId : Int, passwd: String, onValueChange: (String) -> Unit){
    val textpasswd = stringResource(id = textpasswdResId)
    var passwordVisible by remember { mutableStateOf(false) }

    Column(modifier = Modifier.padding(top = 10.dp)) {
        OutlinedTextField(
            value = passwd,
            onValueChange = onValueChange,
            label = { Text(textpasswd) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
            trailingIcon = {
                IconButton(onClick = {
                    passwordVisible = !passwordVisible
                }) {
                    VisibleIconPasswordComponent(passwordVisible)
                }
            },
            shape = RoundedCornerShape(16.dp)
        )
    }
}

@Composable
fun PassWdConfirmTextFieldSign(textpasswdResId : Int,confirmPassword: String, onValueChange: (String) -> Unit){
    val textpasswd = stringResource(id = textpasswdResId)
    var passwordVisible by remember { mutableStateOf(false) }

    Column(modifier = Modifier.padding(top = 10.dp)) {
        OutlinedTextField(
            value = confirmPassword,
            onValueChange = onValueChange,
            label = { Text(textpasswd) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
            trailingIcon = {
                IconButton(onClick = {passwordVisible = !passwordVisible}) {
                    VisibleIconPasswordComponent(passwordVisible)
                }
            },
            shape = RoundedCornerShape(16.dp)
        )
    }
}


// Validation de email
fun isValidEmail(email: String): Boolean {
    val emailRegex = "[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}"
    return email.matches(emailRegex.toRegex())
}

// Vérification mots de passe
fun arePasswordsMatching(password: String, confirmPassword: String): Boolean {
    return password == confirmPassword
}

@Composable
fun ConnexionButtonSign(
    titleResId: Int,
    size: Int,
    colorButton: Color,
    colorText: Color,
    username: String,
    email: String,
    password: String,
    confirmPassword: String,
    viewModel: SignInUserViewModel,
    navController: ()-> Unit
) {
    val title = stringResource(id = titleResId)
    var emailError by remember { mutableStateOf(false) }
    var passwordError by remember { mutableStateOf(false) }
    var passwordErrorEmpty by remember { mutableStateOf(false) }
    var usernameError by remember { mutableStateOf(false) }
    var usernameErrorExist by remember { mutableStateOf(false) }

    val invalidRegex = """^[a-zA-Z0-9]*$""".toRegex()

    Button(
        onClick = {
            emailError = !isValidEmail(email)
            passwordError = !arePasswordsMatching(password, confirmPassword)
            usernameError = username.isBlank() && !username.matches(invalidRegex)
            passwordErrorEmpty = password.isBlank() || confirmPassword.isBlank()

            if (!emailError && !passwordError && !usernameError && !passwordErrorEmpty) {
                usernameErrorExist = !viewModel.createUser(username, email, password)
                if(!usernameErrorExist){
                    navController() // retour à la page login
                }
            }
        },
        colors = ButtonDefaults.buttonColors(containerColor = colorButton),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Text(title, fontSize = size.sp, color = colorText)
    }

    // Afficher erreurs
    if (usernameError) {
        ErrorMessageProfileComponent(R.string.ErrorUserSignUp)
    }

    if (usernameErrorExist) {
        ErrorMessageProfileComponent(R.string.ErrorUserExistSignUp)
    }

    if (emailError) {
        ErrorMessageProfileComponent(R.string.ErrorEmailSignUp)

    }
    if (passwordError) {
        ErrorMessageProfileComponent(R.string.ErrorPasswordSignUp)
    }

    if (passwordErrorEmpty) {
        ErrorMessageProfileComponent(R.string.ErrorPasswordEmpty)
    }


}


@Composable
fun ReturnLogin(titleResId: Int, size: Int, color: Color, navController: () -> Unit) {
    val title = stringResource(id = titleResId)
    Text(
        text = title,
        fontSize = size.sp,
        color = color,
        modifier = Modifier.clickable {
            navController() //  Revenir à la page login
        }
    )
}
