package com.example.development.mainActivity.components

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import android.widget.ScrollView
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.Person
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
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.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.development.R
import com.example.development.domain.utils.Constants
import com.example.development.domain.utils.CustomEmail
import com.example.development.mainActivity.MainViewModel
import com.example.development.model.Menu
import com.example.development.model.User
import com.example.development.ui.theme.OldStandart
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.BucketItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream

@Composable
fun UserProfile(navController: NavHostController, viewModel: MainViewModel){
    val context = LocalContext.current
    var user by remember { mutableStateOf<List<User>>(listOf()) }
    var bucket: ByteArray? = null
    var bytes: ByteArray? = null
    var files: List<BucketItem>? = null
    val surnameFlag = remember { mutableStateOf(false) }
    val nameFlag = remember {mutableStateOf(false)}
    val phoneFlag = remember { mutableStateOf(false) }
    val emailFlag = remember { mutableStateOf(false) }
    val name = remember { mutableStateOf("") }
    val surname = remember { mutableStateOf("") }
    val phoneNumber = remember { mutableStateOf("") }
    val email = remember { mutableStateOf("") }
    val avatar = remember { mutableStateOf(byteArrayOf()) }
    val urii = remember { mutableStateOf("") }
    val launcher =
        rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri == null) return@rememberLauncherForActivityResult
            avatar.value = viewModel.bitmapToByteArray(context, uri)
            urii.value = uri.schemeSpecificPart

        }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            user = Constants.supabase.from("users").select{
                filter{
                    User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                }
            }.decodeList<User>()
            user.forEach { it ->
                it.UID?.let { it1 -> Log.d("P", it1) }
            }
        }
    }
    Box(contentAlignment = Alignment.TopCenter,
        modifier = Modifier
            .fillMaxSize()
    )
    {
        Image(
            painter = painterResource(id = R.drawable.fone),
            contentDescription = "",
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        )
        LazyColumn{
            items(
                user,
                key = { user -> user.UID!! },
            ){
                    user ->
                Row(modifier = Modifier
                    .padding(top = 50.dp)
                    .background(color = Color(230, 235, 239, 50))
                    .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceAround)
                {
                    Text(
                        user.surname + "\n" + user.name,
                        color = Color.White,
                        modifier = Modifier.padding(bottom = 20.dp),
                        fontSize = 30.sp,
                        fontWeight = FontWeight.Bold,
                        fontFamily = OldStandart
                    )
                    /*val imageState = rememberAsyncImagePainter(
                        model = ImageRequest.Builder(LocalContext.current).data(user.avatar)
                            .size(Size.ORIGINAL).build()
                    ).state
                    if (imageState is AsyncImagePainter.State.Error) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(200.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                    if (imageState is AsyncImagePainter.State.Success) {
                        Button(
                            modifier = Modifier
                                .padding()
                                .height(200.dp).width(200.dp),
                            onClick = {},
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(255, 215, 0, 0),
                                contentColor = Color.Gray
                            ),
                            shape = RoundedCornerShape(200.dp),
                            border = BorderStroke(0.dp, color = Color(255, 215, 0, 0))
                        )
                        {
                            Image(
                                modifier = Modifier
                                    .width(200.dp)
                                    .height(200.dp),
                                painter = imageState.painter,
                                contentDescription = "",
                                contentScale = ContentScale.Crop
                            )
                        }
                    }*/
                    Image(
                        painter = painterResource(id = R.drawable.profile),
                        contentDescription = "",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .width(100.dp)
                            .height(100.dp)
                    )
                }
                Row(modifier = Modifier
                    .padding()
                    .background(color = Color(230, 235, 239, 50))
                    .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceAround)
                {
                    Button(
                        modifier = Modifier
                            .padding()
                            .height(70.dp),
                        onClick = {},
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(255, 215, 0),
                            contentColor = Color.Gray
                        ),
                        shape = RoundedCornerShape(10.dp),
                        border = BorderStroke(0.dp, color = Color(255, 215, 0))
                    )
                    {
                        Text(
                            "Персональные\nданные",
                            fontSize = 20.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart,
                            textAlign = TextAlign.Center,
                        )
                    }
                    Button(
                        modifier = Modifier
                            .padding()
                            .height(70.dp),
                        onClick = {navController.navigate("UserProfile2")},
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(230, 235, 239, 0),
                            contentColor = Color.Gray
                        ),
                        shape = RoundedCornerShape(10.dp),
                        border = BorderStroke(0.dp, color = Color(230, 235, 239, 0))
                    )
                    {
                        Text(
                            "История\nбронирования",
                            fontSize = 20.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart,
                            textAlign = TextAlign.Center,
                        )
                    }
                }
                Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally)
                {
                    Text(
                        "Имя",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                    OutlinedTextField(value = name.value,
                        onValueChange = { it -> name.value = it },
                        leadingIcon = { Icon(Icons.Filled.Person, contentDescription = "Имя") },
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color(0XFFF5F5F9),
                            focusedIndicatorColor = Color(0xFFEBEBEB),
                            focusedTextColor = Color.Black,
                            disabledIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            cursorColor = Color(0XFF578FFF),
                            focusedSupportingTextColor = Color(0xFF00000)
                        ),
                        modifier = Modifier
                            .fillMaxWidth(1f)
                            .background(Color(0XFFF5F5F9))
                            .height(height = 56.dp)
                            .width(width = 200.dp),
                        isError = nameFlag.value,
                        placeholder = {
                            Text(
                                modifier = Modifier.fillMaxWidth(),
                                text = user.name,
                                fontWeight = FontWeight.Normal,
                                fontSize = 15.sp,
                                color = Color(0XFF939396)
                            )
                        }
                    )

                    if (name.value.isEmpty()) {
                        nameFlag.value = true
                    } else {
                        nameFlag.value = false
                    }
                    Text(
                        "Фамилия",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                    OutlinedTextField(value = surname.value,
                        onValueChange = { it -> surname.value = it },
                        leadingIcon = { Icon(Icons.Filled.Person, contentDescription = "Фамилия") },
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color(0XFFF5F5F9),
                            focusedIndicatorColor = Color(0xFFEBEBEB),
                            focusedTextColor = Color.Black,
                            disabledIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            cursorColor = Color(0XFF578FFF),
                            focusedSupportingTextColor = Color(0xFF00000)
                        ),
                        modifier = Modifier
                            .fillMaxWidth(1f)
                            .background(Color(0XFFF5F5F9))
                            .height(height = 56.dp)
                            .width(width = 200.dp),
                        isError = surnameFlag.value,
                        placeholder = {
                            Text(
                                modifier = Modifier.fillMaxWidth(),
                                text = user.surname,
                                fontWeight = FontWeight.Normal,
                                fontSize = 15.sp,
                                color = Color(0XFF939396)
                            )
                        }
                    )
                    Text(
                        "E-mail",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                        OutlinedTextField(
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Email
                            ),
                            value = email.value,
                            onValueChange = { newText -> email.value = newText },
                            textStyle = TextStyle(
                                color = Color.Black,
                                fontSize = 15.sp
                            ),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color(0XFFF5F5F9),
                                focusedIndicatorColor = Color(0xFFEBEBEB),
                                focusedTextColor = Color(0XFF578FFF),
                                disabledIndicatorColor = Color.Transparent,
                                unfocusedIndicatorColor = Color.Transparent,
                                cursorColor = Color(0XFF578FFF),
                                focusedSupportingTextColor = Color(0xFF00000)
                            ),
                            modifier = Modifier
                                .fillMaxWidth(1f)
                                .background(Color(0XFFF5F5F9))
                                .height(height = 50.dp)
                                .width(width = 80.dp),
                            placeholder = {
                                Text(
                                    modifier = Modifier.fillMaxWidth(),
                                    text = user.email,
                                    fontSize = 15.sp,
                                    color = Color(0XFF939396)
                                )
                            }
                        )
                    if (email.value.isEmpty())
                    {
                        emailFlag.value = true
                    }
                    else {
                        emailFlag.value = false
                    }
                    Text(
                        "Номер телефона",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                    OutlinedTextField(value = phoneNumber.value, onValueChange = { it -> phoneNumber.value = it },
                        leadingIcon = { Icon(Icons.Filled.Phone, contentDescription = "Номер телефона") },
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color(0XFFF5F5F9),
                            focusedIndicatorColor = Color(0xFFEBEBEB),
                            focusedTextColor = Color.Black,
                            disabledIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            cursorColor = Color(0XFF578FFF),
                            focusedSupportingTextColor = Color(0xFF00000)
                        ),
                        modifier = Modifier
                            .fillMaxWidth(1f)
                            .background(Color(0XFFF5F5F9))
                            .height(height = 56.dp)
                            .width(width = 320.dp),
                        isError = nameFlag.value,

                        placeholder = {
                            Text(
                                modifier = Modifier.fillMaxWidth(),
                                text = user.phone,
                                fontWeight = FontWeight.Normal,
                                fontSize = 15.sp,
                                color = Color(0XFF939396)
                            )
                        }
                    )

                    if (phoneNumber.value.isEmpty()) {
                        phoneFlag.value = true
                    } else {
                        phoneFlag.value = false
                    }
                    Button(
                        modifier = Modifier
                            .padding(0.dp)
                            .width(280.dp),
                        onClick = {navController.navigate("PasswordRecovery")},
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(230, 235, 239, 50),
                            contentColor = Color.Gray
                        ),
                        border = BorderStroke(0.dp, color = Color(230, 235, 239, 50))
                    )
                    {
                        Text(
                            "Сменить пароль",
                            fontSize = 16.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart
                        )
                    }
                    /*Column(modifier = Modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center)
                    {
                        Button(
                            onClick = { launcher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 10.dp),
                            colors = ButtonColors(
                                contentColor = Color.White,
                                containerColor = Color(230, 235, 239, 123),
                                disabledContentColor = Color(0xFF951DDD),
                                disabledContainerColor = Color.White
                            ),
                            shape = RoundedCornerShape(5.dp)
                        ) {
                            if (avatar.value.isEmpty()) {
                                Text(
                                    modifier = Modifier.fillMaxWidth(),
                                    text = "Изменить фото профиля",
                                    fontWeight = FontWeight.Normal,
                                    fontSize = 15.sp,
                                    color = Color.White,
                                    fontFamily = OldStandart,
                                    textAlign = TextAlign.Center
                                )
                            } else {
                                Text(urii.value)
                            }
                        }
                    }*/
                    Button(modifier = Modifier
                        .width(width = 270.dp)
                        .height(height = 40.dp),
                        onClick = {viewModel.UpdatePersonalData(firstName = name.value,
                            secondName = surname.value,
                            email = email.value,
                            phoneNumber = phoneNumber.value)},
                        shape = RoundedCornerShape(23.dp),
                        border = BorderStroke(0.dp, Color(0xFFEBEBEB)),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(255,215,0),
                            contentColor = Color.White)
                    )
                    {
                        Text("СОХРАНИТЬ ИЗМЕНЕНИЯ",
                            fontSize = 16.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart)
                    }
                    Button(modifier = Modifier
                        .width(width = 270.dp)
                        .height(height = 40.dp),
                    onClick = {viewModel.logout(context)},
                    shape = RoundedCornerShape(23.dp),
                    border = BorderStroke(0.dp, Color(0xFFEBEBEB)),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239, 50),
                        contentColor = Color.White)
                    )
                    {
                        Text("ВЫЙТИ",
                            fontSize = 16.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart,
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
        }

    }
}


@Composable
fun UserProfile2(navController: NavHostController, viewModel: MainViewModel)
{
    val context = LocalContext.current
    var user by remember { mutableStateOf<List<User>>(listOf()) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            user = Constants.supabase.from("users").select{
                filter{
                    User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                }
            }.decodeList<User>()
            user.forEach { it ->
                it.UID?.let { it1 -> Log.d("P", it1) }
            }
        }
    }
    Box(contentAlignment = Alignment.TopCenter,
        modifier = Modifier
            .fillMaxSize()
    )
    {
        Image(
            painter = painterResource(id = R.drawable.fone),
            contentDescription = "",
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        )
        Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally)
        {
            Row(
                modifier = Modifier
                    .padding(top = 50.dp)
                    .background(color = Color(230, 235, 239, 50))
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround
            )
            {
                Text(
                    "Имя Фамилия",
                    color = Color.White,
                    modifier = Modifier.padding(),
                    fontSize = 30.sp,
                    fontWeight = FontWeight.Bold,
                    fontFamily = OldStandart
                )
                Image(
                    painter = painterResource(id = R.drawable.profile),
                    contentDescription = "",
                    contentScale = ContentScale.FillWidth,
                    modifier = Modifier
                        .width(100.dp)
                        .height(100.dp)
                )
            }
            Row(
                modifier = Modifier
                    .padding()
                    .background(color = Color(230, 235, 239, 50))
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround
            )
            {
                Button(
                    modifier = Modifier
                        .padding(0.dp),
                    onClick = {},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239, 0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(230, 235, 239, 0))
                )
                {
                    Text(
                        "Персональные\nданные",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        textAlign = TextAlign.Center,
                        fontFamily = OldStandart
                    )
                }
                Button(
                    modifier = Modifier
                        .padding(0.dp),
                    onClick = {},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(255, 215, 0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(255, 215, 0))
                )
                {
                    Text(
                        "История\nбронирования",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        textAlign = TextAlign.Center,
                        fontFamily = OldStandart
                    )
                }
            }
        }
    }
}

@Composable
fun UserProfileForUnauthorizedUser(navController: NavHostController)
{
    Box(contentAlignment = Alignment.TopCenter,
        modifier = Modifier
            .fillMaxSize()
    )
    {
        Image(
            painter = painterResource(id = R.drawable.fone),
            contentDescription = "",
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        )
        Column(modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            )
        {
            Text("Похоже, вы не вошли в систему\nАвторизируйтесь или создайте аккаунт для использования всех функций приложения",
                fontSize = 18.sp,
                color = Color.White,
                fontWeight = FontWeight.Normal,
                fontFamily = OldStandart,
                softWrap = true,
                textAlign = TextAlign.Center)
            Button(
                modifier = Modifier
                    .padding(top = 20.dp),
                onClick = {},
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(255, 215, 0),
                    contentColor = Color.Gray
                ),
                border = BorderStroke(0.dp, color = Color(255, 215, 0))
            )
            {
                Text(
                    "РЕГИСТРАЦИЯ",
                    fontSize = 18.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Normal,
                    textAlign = TextAlign.Center,
                    fontFamily = OldStandart
                )
            }
            Button(
                modifier = Modifier
                    .padding(0.dp),
                onClick = {},
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(255, 215, 0),
                    contentColor = Color.Gray
                ),
                border = BorderStroke(0.dp, color = Color(255, 215, 0))
            )
            {
                Text(
                    "АВТОРИЗАЦИЯ",
                    fontSize = 18.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Normal,
                    textAlign = TextAlign.Center,
                    fontFamily = OldStandart
                )
            }
        }
    }
}