package com.example.what_the_fantasy.ui.screens

import android.content.Context
import android.os.Bundle
import android.util.Patterns
import android.widget.ImageView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.rounded.Face
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
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.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.example.what_the_fantasy.R
import com.example.what_the_fantasy.data.local.QuestionStub
import com.example.what_the_fantasy.data.local.UserStub
import com.example.what_the_fantasy.data.services.IServices
//import com.example.what_the_fantasy.data.local.UserStub.users
import com.example.what_the_fantasy.data.services.ServicesStub
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.theme.What_The_FantasyTheme
import com.example.what_the_fantasy.ui.theme.gradienBox

@Composable
fun ProfilPage(index: Int,
               navFavorite: (Int) -> Unit,
               navAccueil: (Int) -> Unit,
               navQuiz: (Int) -> Unit,
               navUnLog: () -> Unit,
               services: IServices
) {
    val user = services.getUserById(index) ?: return

    NavBar(onProfile = true,
        index = index,
        navControllerFavorite = navFavorite,
        navControllerAccueil = navAccueil,
        navControllerProfil = {},
        navControllerQuiz = navQuiz
    ) {

        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFF100C1B)),
            contentAlignment = Alignment.Center
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth(0.9f)
                    .padding(20.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(gradienBox)
                    .padding(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

            // Titre
            TitlePageComponent(R.string.titleProfile,  Color.White)
            SpaceHeightComponent(16)

            // Image de profil
            ImageProfil(user.imgUrl, 120)
            SpaceHeightComponent(16)

            EditUsername(user.username, index, services)// Édition du Username
            SpaceHeightComponent(16)

            EditEmail(user.email,index, services)// Édition du Email
            Spacer(modifier = Modifier.height(8.dp))

            EditPasswd(index, services)
            SpaceHeightComponent(16)

            // Bouton
            //ButtonProfile(R.string.ButtonAddQuoteprofile, 18, Color.Black, Color.White,navUnLog) // Pas encore de navigation definie
            //SpaceHeightComponent(16)
            ButtonProfile(R.string.ButtonLanguageprofile, 18, Color.Black, Color.White,navUnLog) // Pas encore de navigation definie
            SpaceHeightComponent(16)
            ButtonProfile(R.string.ButtonUnlogprofile, 18, Color.Black, Color.White, navUnLog)

            }
        }
    }
}


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

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

@Composable
fun EditEmail(userEmail: String, index: Int, service: IServices) {
    var email by remember { mutableStateOf(userEmail) }
    var isEditingEmail by remember { mutableStateOf(false) }
    var emailError by remember { mutableStateOf(false) }

    fun onDoneEditing() {
        service.EditEmail(email, index)
        isEditingEmail = false
    }

    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 = Color.White, 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 = Color.White
        )
        Icon(
            imageVector = Icons.Default.Edit,
            contentDescription = "Modifier",
            tint = Color.White,
            modifier = Modifier.size(16.dp).padding(start = 8.dp)
        )
    }
}



@Composable
fun EditUsername(userName: String, index: Int, service : IServices) {
    var username by remember { mutableStateOf(userName) }
    var isEditingUsername by remember { mutableStateOf(false) }

    fun onDoneEditing() {
        service.EditUsername(username, index)
        isEditingUsername = false
    }

    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 = Color.White, 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 = Color.White
        )
        Icon(
            imageVector = Icons.Default.Edit,
            contentDescription = "Modifier",
            tint = Color.White,
            modifier = Modifier.size(16.dp).padding(start = 8.dp)
        )
    }
}



@Composable
fun EditPasswd(index: Int, service: IServices) {
    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
        service.EditPasswd(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() // Appeler la fonction onDoneEditing() pour mettre à jour le mot de passe
                }
            }
        )
    } else {
        DisplayPassword(onEdit = { isEditingPassword = true }) // Afficher l'option 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 = Color.White, 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) }) {
                // Ajout d'une icône pour montrer/masquer le mot de passe
            }
        },
        isError = isError
    )
}

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

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

@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)
    }
}