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.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.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.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 com.example.what_the_fantasy.Logs.LogsUsers
import com.example.what_the_fantasy.R
import com.example.what_the_fantasy.data.model.User
import com.example.what_the_fantasy.data.services.IServices
import com.example.what_the_fantasy.ui.components.ErrorMessageProfileComponent
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.hashPassword
import com.example.what_the_fantasy.ui.theme.colorBackground
import com.example.what_the_fantasy.ui.theme.gradienBox

@Composable
fun LoginPage(navControllerSignUp: () -> Unit, navControllerProfil: (Int) -> Unit, services : IServices) {
    val users = services.getAllUsers()

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background),
        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.titleLogin, MaterialTheme.colorScheme.primary)
            SpaceHeightComponent(20)
            ConnexionButtonLogin(users,IdentifiantTextField(R.string.IdentifiantLogin), PassWdTextField(R.string.PasswdLogin), R.string.ButtonLogin,18, Color.White, Color.Black,navControllerProfil)
            SpaceHeightComponent(16)
            CreateAccountButton(R.string.ButtonCreateLogin,12, MaterialTheme.colorScheme.primary, navControllerSignUp)
        }
    }
}




@Composable
fun IdentifiantTextField(textIdentifiantResId : Int) : String{
    val textIdentifiant = stringResource(id = textIdentifiantResId)
    var identifiant by remember { mutableStateOf("") }
    Column(modifier = Modifier.padding(top = 16.dp)) {
        OutlinedTextField(
            value = identifiant,
            onValueChange = { identifiant = it },
            label = { Text(textIdentifiant) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
            shape = RoundedCornerShape(16.dp)
        )
    }
    return identifiant;
}

@Composable
fun PassWdTextField(textpasswdResId : Int) : String{
    val textpasswd = stringResource(id = textpasswdResId)
    var passwd by remember { mutableStateOf("") }
    var passwordVisible by remember { mutableStateOf(false) }
    Column(modifier = Modifier.padding(top = 10.dp, bottom = 30.dp)) {
        OutlinedTextField(
            value = passwd,
            onValueChange = { passwd = it },
            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 }) {
                }
            },
            shape = RoundedCornerShape(16.dp)
        )
    }
    return passwd;
}


@Composable
fun ConnexionButtonLogin(userStub : List<User>, id : String, passwd : String, titleResId : Int, size : Int, colorButton : Color, colorText : Color, navController: (Int) -> Unit){
    val title = stringResource(id = titleResId)
    var showError by remember { mutableStateOf(false) }
    Button(
        onClick = { showError = !validLogin(id, passwd, userStub, navController)
                  },
        colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.background),
        modifier = Modifier
            .fillMaxWidth(),
    ) {
        Text(title, fontSize = size.sp, color = MaterialTheme.colorScheme.onBackground)
    }

    if(showError){
        ErrorMessageProfileComponent(R.string.ErrorLogin)
    }
}


fun validLogin(identifiant : String, passwd : String, users : List<User>, navController: (Int) -> Unit): Boolean {
    val logsUser = LogsUsers() //gestion des logs pour les utilisateurs

    users.forEachIndexed { index, user ->
        val hashPassWd = hashPassword(passwd)
        if (user.username == identifiant && user.password == hashPassWd) {
            navController(index)
            logsUser.logInformationUserConnect(user, "UserConnect")
            return true
        }
    }
    return false
}

@Composable
fun CreateAccountButton(titleResId : Int, size : Int, color : Color, navController: () -> Unit) {
    val title = stringResource(id = titleResId)
    Text(
        text = title,
        fontSize = size.sp,
        color = MaterialTheme.colorScheme.onBackground,
        modifier = Modifier.clickable {
            navController()
        }
    )
}