package com.example.pmulabs.screensMobile.authScreens

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
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.draw.rotate
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
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.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.pmulabs.designElem.elem.ValidateEmail
import com.example.pmulabs.designElem.elem.isValidEmail
import com.example.pmulabs.designElem.statDesign.LeftCircles
import com.example.pmulabs.designElem.statDesign.LogoMobile
import com.example.pmulabs.designElem.statDesign.RightCircles
import com.example.pmulabs.graphs.AuthScreen
import com.example.pmulabs.graphs.Graph
import com.example.pmulabs.room.models.User
import com.example.pmulabs.viewModels.AppViewModelProvider
import com.example.pmulabs.viewModels.CurrentUserViewModel
import com.example.pmulabs.viewModels.RegisterScreenViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegisterScreen(navController: NavController, modifier: Modifier = Modifier,registerScreenViewModel: RegisterScreenViewModel = viewModel(factory = AppViewModelProvider.Factory), currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)) {

    var emailValue by rememberSaveable { mutableStateOf("") }
    var passwordValue by rememberSaveable { mutableStateOf("") }
    var nicknameValue by rememberSaveable { mutableStateOf("") }
    val coroutineScope = rememberCoroutineScope()
    registerScreenViewModel.setUserList()
    var users = mutableStateOf<List<User>>(emptyList())
    registerScreenViewModel.users.observeForever { userList ->
        users.value = userList
    }

    var passwordVisibility by rememberSaveable { mutableStateOf(false) }
    val emailRegex = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+".toRegex()

    Box(
        modifier = modifier
            .requiredWidth(width = 412.dp)
            .requiredHeight(height = 915.dp)
            .background(color = Color.White)
    ) {
        Box(
            modifier = Modifier
                .align(alignment = Alignment.TopStart)
                .offset(
                    x = 128.dp,
                    y = 730.dp
                )
                .requiredWidth(width = 381.dp)
                .requiredHeight(height = 268.dp)
                .rotate(degrees = 8.33f)
        ) {
            RightCircles()
        }
        Box(
            modifier = Modifier
                .align(alignment = Alignment.TopStart)
                .offset(
                    x = (-111.28436279296875).dp,
                    y = (-96.86965942382812).dp
                )
                .requiredWidth(width = 250.dp)
                .requiredHeight(height = 290.dp)
                .rotate(degrees = 12.96f)
        ) {
            LeftCircles()
        }

    }

    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {

        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.8f)
                .clip(RoundedCornerShape(15.dp))
                .background(Color.Transparent)
                .padding(10.dp)
        ) {

            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.Transparent), contentAlignment = Alignment.TopCenter
                ) {

                    LogoMobile(
                        modifier = Modifier
                            .align(alignment = Alignment.TopStart)
                            .fillMaxWidth()
                            .requiredHeight(height = 131.dp)
                    )

                }
                Text(
                    text = "Please, Sign In to your account",
                    color = Color(0xff7d7dbd),
                    textAlign = TextAlign.Center,
                    style = TextStyle(
                        fontSize = 20.sp
                    ),
                    modifier = modifier
                        .requiredWidth(width = 436.dp)
                        .requiredHeight(height = 27.dp)
                )
                Spacer(modifier = Modifier.padding(10.dp))

                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    TextField(
                        value = nicknameValue,
                        onValueChange = {
                            nicknameValue = it
                        },
                        colors = TextFieldDefaults.textFieldColors(
                            containerColor = Color.White
                        ),
                        modifier = Modifier
                            .requiredWidth(width = 269.dp)
                            .requiredHeight(height = 53.dp)
                            .shadow(shape = RoundedCornerShape(40.dp), elevation = 5.dp)
                            .clip(shape = RoundedCornerShape(40.dp)),
                        label = { Text("Nickname") },
                        placeholder = { Text("Nickname") },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                        singleLine = true,
                    )
                    Spacer(modifier = Modifier.padding(3.dp))
                    ValidateEmail(emailValue, { emailValue = it })
                    Spacer(modifier = Modifier.padding(3.dp))
                    TextField(
                        value = passwordValue,
                        onValueChange = { passwordValue = it },
                        colors = TextFieldDefaults.textFieldColors(
                            containerColor = Color.White
                        ),
                        modifier = modifier
                            .requiredWidth(width = 269.dp)
                            .requiredHeight(height = 53.dp)
                            .shadow(shape = RoundedCornerShape(40.dp), elevation = 5.dp)
                            .clip(shape = RoundedCornerShape(40.dp)),
                        label = { Text("Password") },
                        singleLine = true,
                        placeholder = { Text("Password") },
                        visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                        trailingIcon = {
                            val image = if (passwordVisibility)
                                Icons.Filled.Visibility
                            else Icons.Filled.VisibilityOff

                            val description =
                                if (passwordVisibility) "Hide password" else "Show password"

                            IconButton(onClick = { passwordVisibility = !passwordVisibility }) {
                                Icon(imageVector = image, description)
                            }
                        }
                    )

                    Spacer(modifier = Modifier.padding(10.dp))
                    Button(
                        colors = ButtonColors(
                            containerColor = Color(0xff423a99),
                            disabledContainerColor = Color(0xff423a99),
                            contentColor = Color.White,
                            disabledContentColor = Color.White
                        ),
                        onClick = {
                            var isExist = false;
                            if (passwordValue.isNotEmpty() && isValidEmail(emailValue) && nicknameValue.isNotEmpty()) {
                                users.value.forEach { user ->
                                    if (user.email == emailValue || user.nickname == nicknameValue) {
                                        Log.d("User already exist. User id: ", user.id.toString())
                                        isExist = true
                                    }
                                }
                                if (!isExist) {
                                    val newUser = User(null, nicknameValue, emailValue, passwordValue, "user")
                                    coroutineScope.launch {
                                        val insertResult = async {
                                            registerScreenViewModel.insertUser(newUser)
                                        }

                                        insertResult.await()

                                        registerScreenViewModel.setUserList()
                                        registerScreenViewModel.users.observeForever { userList ->
                                            users.value = userList
                                            Log.println(Log.ASSERT, "UsersList", users.value.toString())
                                            users.value?.forEach { user ->
                                                if (user.password == passwordValue && user.email == emailValue) {
                                                    currentUserViewModel.setArgument(user.id.toString())
                                                    navController.navigate(route = Graph.passUserId(user.id.toString()))
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth(0.5f)
                            .height(50.dp)
                    ) {
                        Text(text = "Sign Up", fontSize = 20.sp)
                    }

                    Spacer(modifier = Modifier.padding(0.dp))

                    Text(
                        text = "Do you have an account? Sign In",
                        color = Color(0xff7d7dbd),
                        textAlign = TextAlign.Center,
                        style = TextStyle(
                            fontSize = 20.sp
                        ),
                        modifier = Modifier
                            .fillMaxSize()
                            .offset(
                                x = 0.dp,
                                y = 75.dp
                            )
                            .clickable {
                                navController.navigate(route = AuthScreen.Entry.route)
                                {
                                    popUpTo(AuthScreen.Splash.route)
                                }
                            }
                    )
                    Spacer(modifier = Modifier.padding(20.dp))

                }
            }
        }
    }
}
