package com.example.what_the_fantasy.ui.screens

import android.util.Log
import android.util.Patterns
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.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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Edit
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.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.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
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 coil.compose.AsyncImage
import com.example.what_the_fantasy.logs.LogsUsers
import com.example.what_the_fantasy.R
import com.example.what_the_fantasy.ui.components.ErrorMessageProfileComponent
import com.example.what_the_fantasy.ui.components.NavBar
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.VisibleIconPasswordComponent
import com.example.what_the_fantasy.ui.states.CurrentUserState
import com.example.what_the_fantasy.ui.viewModels.CurrentUserViewModel

@Composable
fun ProfilPage(navFavorite: () -> Unit,
               navAccueil: () -> Unit,
               navQuiz: () -> Unit,
               navUnLog: () -> Unit,
               navSubmitQuote: () -> Unit,
               navSearch: () -> Unit,
               currentUserVM : CurrentUserViewModel,
               currentUserState : CurrentUserState,
) {

    NavBar(onProfile = true,
        currentUserVM = currentUserVM,
        currentUserState = currentUserState,
        navControllerFavorite = navFavorite,
        navControllerAccueil = navAccueil,
        navControllerQuiz = navQuiz,
        navControllerSearch = navSearch
    ) {

        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
            ) {

                // Titre
                TitlePageComponent(R.string.titleProfile,  MaterialTheme.colorScheme.onBackground)
                SpaceHeightComponent(16)

            // Image de profil
            ImageProfil(currentUserState.imagePath, 120)
            SpaceHeightComponent(16)

            EditUsername(currentUserState.username, currentUserState.id, currentUserVM)// Édition du Username
            SpaceHeightComponent(16)

            EditEmail(currentUserState.email,currentUserState.id, currentUserVM)// Édition du Email
            Spacer(modifier = Modifier.height(8.dp))

            EditPasswd(currentUserState.id, currentUserVM)
            SpaceHeightComponent(16)

            // Bouton
            ButtonProfile(R.string.ButtonAddQuoteprofile, 18, MaterialTheme.colorScheme.primary,MaterialTheme.colorScheme.background,navSubmitQuote) // Pas encore de navigation definie
            SpaceHeightComponent(16)
            ButtonLanguage(R.string.ButtonLanguageprofile, 18, MaterialTheme.colorScheme.primary,MaterialTheme.colorScheme.background,currentUserVM, currentUserState)
            SpaceHeightComponent(16)
            ButtonUnLog(R.string.ButtonUnlogprofile, 18,MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.background, navUnLog,currentUserVM)



            }
        }
    }
}


@Composable
fun ImageProfil(imgProfil : String, size :Int){

    AsyncImage(
        model = imgProfil,
        contentDescription = "Photo de profil",
        modifier = Modifier
            .size(size.dp)
            .clip(CircleShape)
    )
}

@Composable
fun EditEmail(emailState: String, index: Int, currentUserVM: CurrentUserViewModel) {
    var email by remember { mutableStateOf(emailState) }
    var isEditingEmail by remember { mutableStateOf(false) }
    var emailError by remember { mutableStateOf(false) }

    fun onDoneEditing() {
        isEditingEmail =!currentUserVM.editEmail(email, index)

    }

    if (isEditingEmail) {
        EmailEditingField(
            email = email,
            onEmailChange = { newEmail ->
                email = newEmail
                emailError = !Patterns.EMAIL_ADDRESS.matcher(newEmail).matches() // Validation email
            },
            onDone = {
                if (!emailError) {
                    onDoneEditing()
                }
            },
            emailError = emailError
        )
    } else {
        DisplayEmail(email = email, onEdit = { isEditingEmail = true })
    }
}

@Composable
fun EmailEditingField(
    email: String,
    onEmailChange: (String) -> Unit,
    onDone: () -> Unit,
    emailError: Boolean
) {
    OutlinedTextField(
        value = email,
        onValueChange = onEmailChange,
        modifier = Modifier.fillMaxWidth(),
        textStyle = TextStyle(color = MaterialTheme.colorScheme.primary, fontSize = 18.sp),
        singleLine = true,
        keyboardOptions = KeyboardOptions.Default.copy(
            keyboardType = KeyboardType.Email,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = { onDone() }
        ),
        trailingIcon = {
            IconButton(onClick = { if (!emailError) onDone() }) {
                Icon(imageVector = Icons.Default.CheckCircle, contentDescription = "Valider")
            }
        },
        isError = emailError
    )

    if (emailError) {
        ErrorMessageProfileComponent(R.string.ErrorEmailprofile)
    }
}


@Composable
fun DisplayEmail(email: String, onEdit: () -> Unit) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.clickable { onEdit() }
    ) {
        Text(
            text = email,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        Icon(
            imageVector = Icons.Default.Edit,
            contentDescription = "Modifier",
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(16.dp).padding(start = 8.dp)
        )
    }
}



@Composable
fun EditUsername(usernameState: String, index: Int, currentUserVM : CurrentUserViewModel) {
    var username by remember { mutableStateOf(usernameState) }
    var isEditingUsername by remember { mutableStateOf(false) }

    fun onDoneEditing() {
        isEditingUsername= !currentUserVM.editUsername(username, index)
    }

    if (isEditingUsername) {
        UsernameEditingField(
            username = username,
            onUsernameChange = { username = it },
            onDone = { onDoneEditing() }
        )
    } else {
        DisplayUsername(username = username, onEdit = { isEditingUsername = true })
    }
}

@Composable
fun UsernameEditingField(
    username: String,
    onUsernameChange: (String) -> Unit,
    onDone: () -> Unit
) {
    OutlinedTextField(
        value = username,
        onValueChange = onUsernameChange,
        modifier = Modifier.fillMaxWidth(),
        textStyle = TextStyle(color = MaterialTheme.colorScheme.primary, fontSize = 18.sp),
        singleLine = true,
        keyboardOptions = KeyboardOptions.Default.copy(
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = { onDone() }
        ),
        trailingIcon = {
            IconButton(onClick = { onDone() }) {
                Icon(imageVector = Icons.Default.CheckCircle, contentDescription = "Valider")
            }
        }
    )
}

@Composable
fun DisplayUsername(username: String, onEdit: () -> Unit) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.clickable { onEdit() }
    ) {
        Text(
            text = username,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        Icon(
            imageVector = Icons.Default.Edit,
            contentDescription = "Modifier",
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(16.dp).padding(start = 8.dp)
        )
    }
}



@Composable
fun EditPasswd(index: Int, currentUserVM: CurrentUserViewModel) {
    var password by remember { mutableStateOf("*******") } // Mot de passe actuel (affiché comme un masque)
    var isEditingPassword by remember { mutableStateOf(false) }
    var newPassword by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var passwordVisible by remember { mutableStateOf(false) }
    var passwordError by remember { mutableStateOf(false) }

    // Fonction pour finaliser l'édition du mot de passe et appeler la méthode EditPasswd2
    fun onDoneEditing() {
        // Appeler EditPasswd pour mettre à jour le mot de passe de l'utilisateur
        currentUserVM.editPassword(newPassword, index)
        isEditingPassword = false
    }

    if (isEditingPassword) {
        PasswordEditingFields(
            newPassword = newPassword,
            confirmPassword = confirmPassword,
            onNewPasswordChange = { newPassword = it },
            onConfirmPasswordChange = {
                confirmPassword = it
                passwordError = newPassword != it // Vérifier si les mots de passe correspondent
            },

            passwordVisible = passwordVisible,
            onPasswordVisibilityChange = { passwordVisible = it },
            passwordError = passwordError,
            onDone = {
                if (!passwordError && newPassword.isNotEmpty()) {
                    onDoneEditing() // pour mettre à jour le mot de passe
                }
            }
        )
    } else {
        DisplayPassword(onEdit = { isEditingPassword = true }) // pour modifier le mot de passe
    }

}

@Composable
fun PasswordEditingFields(
    newPassword: String,
    confirmPassword: String,
    onNewPasswordChange: (String) -> Unit,
    onConfirmPasswordChange: (String) -> Unit,
    passwordVisible: Boolean,
    onPasswordVisibilityChange: (Boolean) -> Unit,
    passwordError: Boolean,
    onDone: () -> Unit
) {
    Column {
        val text = stringResource(id = R.string.NewPasswdprofile)
        PasswordTextField(
            value = newPassword,
            onValueChange = onNewPasswordChange,
            label = text,
            passwordVisible = passwordVisible,
            onPasswordVisibilityChange = onPasswordVisibilityChange
        )

        Spacer(modifier = Modifier.height(8.dp))

        val textConfirm = stringResource(id = R.string.ConfirmNewPasswdprofile)
        PasswordTextField(
            value = confirmPassword,
            onValueChange = onConfirmPasswordChange,
            label = textConfirm,
            passwordVisible = passwordVisible,
            onPasswordVisibilityChange = onPasswordVisibilityChange,
            isError = passwordError,
            onDone = onDone
        )

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

        Spacer(modifier = Modifier.height(8.dp))

        SaveButton(onClick = onDone)
    }
}

@Composable
fun PasswordTextField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String,
    passwordVisible: Boolean,
    onPasswordVisibilityChange: (Boolean) -> Unit,
    isError: Boolean = false,
    onDone: (() -> Unit)? = null
) {
    OutlinedTextField(
        value = value,
        onValueChange = onValueChange,
        label = { Text(label) },
        modifier = Modifier.fillMaxWidth(),
        textStyle = TextStyle(color = MaterialTheme.colorScheme.primary, fontSize = 18.sp),
        singleLine = true,
        keyboardOptions = KeyboardOptions.Default.copy(
            keyboardType = KeyboardType.Password,
            imeAction = if (onDone != null) ImeAction.Done else ImeAction.Next
        ),
        keyboardActions = onDone?.let {
            KeyboardActions(onDone = { it() })
        } ?: KeyboardActions.Default,
        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
        trailingIcon = {
            IconButton(onClick = { onPasswordVisibilityChange(!passwordVisible) }) {
                VisibleIconPasswordComponent(passwordVisible)
            }
        },
        isError = isError
    )
}

@Composable
fun SaveButton(onClick: () -> Unit) {
    Button(
        onClick = onClick,
        colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.onPrimary),
        modifier = Modifier.fillMaxWidth()
    ) {
        val text = stringResource(id = R.string.ButtonSaveprofile)
        Text(text,
            fontSize = 18.sp,
            color = MaterialTheme.colorScheme.primary)
    }
}

@Composable
fun DisplayPassword(onEdit: () -> Unit) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.clickable { onEdit() }
    ) {
        Text(
            text = "*****",
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        Icon(
            imageVector = Icons.Default.Edit,
            contentDescription = "Modifier",
            tint =MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(16.dp).padding(start = 8.dp)
        )
    }
}

@Composable
fun ButtonUnLog(textResId : Int, size :Int, colorTexte : Color,colorButton : Color, navController: () -> Unit, currentUserVM: CurrentUserViewModel){
    val text = stringResource(id = textResId)
    val logsUser = LogsUsers() //gestion des logs pour les utilisateurs

    Button(
        onClick = {
            currentUserVM.clearCurrentUser()
            navController()
            logsUser.unlogInformationUserConnect("UserUnLog")

                  },
        colors = ButtonDefaults.buttonColors(containerColor = colorButton),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Text(text, fontSize = size.sp, color = colorTexte)
    }
}

@Composable
fun ButtonLanguage(textResId : Int, size :Int,colorTexte : Color, colorButton : Color, currentUserVM: CurrentUserViewModel, currentUserState : CurrentUserState){
    val text = stringResource(id = textResId)

    Button(
        onClick = {
            currentUserVM.editLangue(currentUserState.id)
        },
        colors = ButtonDefaults.buttonColors(containerColor = colorButton),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Text("${text} (${currentUserState.langage})", fontSize = size.sp, color = colorTexte)
    }
}

@Composable
fun ButtonProfile(textResId : Int, size :Int,colorTexte : Color, colorButton : Color,navController: () -> Unit){
    val text = stringResource(id = textResId)

    Button(
        onClick = {
            navController()
        },
        colors = ButtonDefaults.buttonColors(containerColor = colorButton),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Text(text, fontSize = size.sp, color = colorTexte)
    }
}