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.Toast
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.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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
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.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
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.State
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.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.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.development.R
import com.example.development.domain.utils.Constants
import com.example.development.domain.utils.CustomEmail
import com.example.development.domain.utils.CustomPassword
import com.example.development.ui.theme.OldStandart
import com.example.development.mainActivity.MainViewModel
import com.example.development.model.User
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.postgrest.from
import io.ktor.http.ContentType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream

@Composable
fun RegistrationScreen(navController: NavHostController, viewModel: MainViewModel) {
    val context = LocalContext.current
    val email = remember { mutableStateOf("") }
    val password = remember { mutableStateOf("") }
    val checkPassword = remember { mutableStateOf("") }
    val flag = remember { mutableStateOf(false) }
    val flagNotNull = remember { mutableStateOf(false) }
    val checkEmail = remember { mutableStateOf(false) }
    var user by remember { mutableStateOf<List<User>>(listOf()) }
    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.SpaceAround, horizontalAlignment = Alignment.CenterHorizontally)
        {
            Column(verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally)
            {
                Image(
                    painter = painterResource(id = R.drawable.logo),
                    contentDescription = "",
                    contentScale = ContentScale.FillHeight,
                    modifier = Modifier
                        .height(150.dp)
                        .width(150.dp)
                )
            }
            Column(verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, )
            {
                    Text(
                    "РЕГИСТРАЦИЯ",
                    color = Color.White,
                    modifier = Modifier.padding(bottom = 50.dp),
                    fontSize = 32.sp,
                    fontWeight = FontWeight.Bold,
                    fontFamily = OldStandart
                )
                Column(
                    modifier = Modifier
                        .padding(),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                )
                {
                    Box(
                        modifier = Modifier
                            .clip(RoundedCornerShape(10.dp))
                            .background(Color(0XFFE8EFFF))
                            .width(300.dp)
                            .height(50.dp)
                    ) {
                        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 = "Введите e-mail",
                                    fontSize = 15.sp,
                                    color = Color(0XFF939396)
                                )
                            }
                        )
                    }
                    Column(
                        modifier = Modifier
                            .padding(top = 0.dp)
                    )
                    {
                        Box(
                            modifier = Modifier
                                .clip(RoundedCornerShape(10.dp))
                                .background(Color(0XFFE8EFFF))
                                .width(300.dp)
                                .height(50.dp)
                        )
                        {
                            val checked1 = remember { mutableStateOf(false) }
                            OutlinedTextField(
                                keyboardOptions = KeyboardOptions(
                                    keyboardType = KeyboardType.Password
                                ),
                                trailingIcon = {
                                    IconToggleButton(
                                        checked = checked1.value,
                                        onCheckedChange = { checked1.value = it }) {
                                        Icon(
                                            if (checked1.value) {
                                                painterResource(id = R.drawable.eye_open)
                                            } else {
                                                painterResource(id = R.drawable.eye_close)
                                            },
                                            contentDescription = "Скрыть пароль",
                                            tint = Color(0XFF939396),
                                            modifier = Modifier.width(20.dp)
                                        )
                                    }
                                },
                                visualTransformation = if (checked1.value) VisualTransformation.None else PasswordVisualTransformation(),
                                value = password.value,
                                onValueChange = { newText -> password.value = newText },
                                textStyle = TextStyle(
                                    color = Color.Black,
                                    fontSize = 15.sp
                                ),
                                colors = TextFieldDefaults.colors(
                                    focusedContainerColor = Color(0XFFF5F5F9),
                                    focusedIndicatorColor = Color(0xFFEBEBEB),
                                    focusedTextColor = Color(0XFF578FFF),
                                    disabledIndicatorColor = Color.White,
                                    unfocusedIndicatorColor = Color.White,
                                    cursorColor = Color(0XFF578FFF),
                                    focusedSupportingTextColor = Color(0xFF00000)
                                ),
                                modifier = Modifier
                                    .fillMaxWidth(1f)
                                    .background(Color(0XFFF5F5F9))
                                    .height(height = 50.dp)
                                    .width(width = 200.dp),
                                placeholder = {
                                    Text(
                                        modifier = Modifier.fillMaxWidth(),
                                        text = "Введите пароль",
                                        fontSize = 15.sp,
                                        color = Color(0XFF939396)
                                    )
                                }
                            )
                        }
                        Box(
                            modifier = Modifier
                                .clip(RoundedCornerShape(10.dp))
                                .background(Color(0XFFE8EFFF))
                                .width(300.dp)
                                .height(50.dp)
                        )
                        {
                            val checked = remember { mutableStateOf(false) }
                            OutlinedTextField(
                                keyboardOptions = KeyboardOptions(
                                    keyboardType = KeyboardType.Password
                                ),
                                trailingIcon = {
                                    IconToggleButton(
                                        checked = checked.value,
                                        onCheckedChange = { checked.value = it }) {
                                        Icon(
                                            if (checked.value) {
                                                painterResource(id = R.drawable.eye_open)
                                            } else {
                                                painterResource(id = R.drawable.eye_close)
                                            },
                                            contentDescription = "Скрыть пароль",
                                            tint = Color(0XFF939396),
                                            modifier = Modifier.width(20.dp)
                                        )
                                    }
                                },
                                visualTransformation = if (checked.value) VisualTransformation.None else PasswordVisualTransformation(),
                                value = checkPassword.value,
                                onValueChange = { newText -> checkPassword.value = newText },
                                textStyle = TextStyle(
                                    color = Color.Black,
                                    fontSize = 15.sp
                                ),
                                colors = TextFieldDefaults.colors(
                                    focusedContainerColor = Color(0XFFF5F5F9),
                                    focusedIndicatorColor = Color(0xFFEBEBEB),
                                    focusedTextColor = Color(0XFF578FFF),
                                    disabledIndicatorColor = Color.White,
                                    unfocusedIndicatorColor = Color.White,
                                    cursorColor = Color(0XFF578FFF),
                                    focusedSupportingTextColor = Color(0xFF00000)
                                ),
                                modifier = Modifier
                                    .fillMaxWidth(1f)
                                    .background(Color(0XFFF5F5F9))
                                    .height(height = 50.dp)
                                    .width(width = 200.dp),
                                placeholder = {
                                    Text(
                                        modifier = Modifier.fillMaxWidth(),
                                        text = "Повторите пароль",
                                        fontSize = 15.sp,
                                        color = Color(0XFF939396)
                                    )
                                }
                            )
                        }
                        if (email.value == "" || password.value == "" || checkPassword.value == "")
                        {
                            flagNotNull.value = false
                        }
                        else{
                            flagNotNull.value = true
                        }
                        if (password.value == checkPassword.value)
                        {
                            flag.value = true
                        }
                        else
                        {
                            flag.value = false
                        }
                    }
                    Button(
                        modifier = Modifier
                            .padding(top = 15.dp)
                            .height(50.dp),
                        onClick = {
                            if (flagNotNull.value) { if (flag.value) {
                                viewModel.onSignUpEmail(email.value,password.value);
                                navController.navigate("RegistrationScreen2")}
                            else { Toast.makeText(context, "Пароли не совпадают", Toast.LENGTH_SHORT).show() }
                            }
                            else { Toast.makeText(context, "Заполнены не все поля", Toast.LENGTH_SHORT).show() }
                        },
                        shape = RoundedCornerShape(23.dp),
                        border = BorderStroke(1.dp, Color(255,215,0)),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(255, 215, 0),
                            contentColor = Color.White
                        )
                    )
                    {
                        Text("ЗАРЕГИСТРИРОВАТЬСЯ", fontSize = 20.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart)
                    }
                    Button(
                        modifier = Modifier
                            .padding(top = 5.dp)
                            .height(50.dp)
                            .width(280.dp),
                        onClick = {navController.navigate("MainPage")},
                        shape = RoundedCornerShape(23.dp),
                        border = BorderStroke(1.dp, Color(255,215,0, 0)),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(255, 215, 0, 0),
                            contentColor = Color.White
                        )
                    )
                    {
                        Text("Продолжить без входа", fontSize = 18.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Normal,
                            fontFamily = OldStandart)
                    }
                }
            }

            Column(
                modifier = Modifier.padding(),
                verticalArrangement = Arrangement.Bottom,
                horizontalAlignment = Alignment.CenterHorizontally
            )
            {
                Text("Или войдите с помощью", fontSize = 16.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Normal,
                    fontFamily = OldStandart)
                Button(
                    modifier = Modifier
                        .padding(top = 10.dp)
                        .height(70.dp)
                        .width(270.dp),
                    onClick = {},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239, 123),
                        contentColor = Color.Gray
                    ),
                    shape = RoundedCornerShape(10.dp),
                    border = BorderStroke(0.dp, color = Color(230, 235, 239,123))
                )
                {
                    Text(
                        "Войти с Google",
                        fontSize = 20.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                }
                Button(
                    modifier = Modifier
                        .padding(top = 10.dp),
                    onClick = {navController.navigate("AuthorizationScreen")},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239,0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(230, 235, 239, 0))
                )
                {
                    Text(
                        "Войти в существующий аккаунт",
                        fontSize = 18.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                }
            }
        }
    }
}

@Composable
fun RegistrationScreen2(navController: NavHostController, viewModel: MainViewModel) {
    val context = LocalContext.current
    val flag = remember {mutableStateOf(false)}
    val surnameFlag = remember { mutableStateOf(false) }
    val nameFlag = remember {mutableStateOf(false)}
    val phoneFlag = remember { mutableStateOf(false) }
    val name = remember { mutableStateOf("") }
    val surname = remember { mutableStateOf("") }
    val phoneNumber = 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

        }

    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.fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center)
        {
            Text("Для завершения регистрации введите следующие данные:",
                color = Color.White,
                modifier = Modifier.padding(bottom = 100.dp),
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                fontFamily = OldStandart
            )
            Column()
            {
                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 = "Фамилия",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )

                if (surname.value.isEmpty()) {
                    surnameFlag.value = true
                    Text("Введите фамилию", color = Color.Red, fontSize = 10.sp)
                } else {
                    surnameFlag.value = false
                }
            }
            Spacer(modifier = Modifier.height(20.dp))
            Column {
                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 = 320.dp),
                    isError = nameFlag.value,

                    placeholder = {
                        Text(
                            modifier = Modifier.fillMaxWidth(),
                            text = "Имя",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )

                if (name.value.isEmpty()) {
                    nameFlag.value = true
                    Text("Введите имя", color = Color.Red, fontSize = 10.sp)
                } else {
                    nameFlag.value = false
                }

            }
            Spacer(modifier = Modifier.height(20.dp))
            Column {
                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 = "Номер телефона",
                            fontWeight = FontWeight.Normal,
                            fontSize = 15.sp,
                            color = Color(0XFF939396)
                        )
                    }
                )

                if (phoneNumber.value.isEmpty()) {
                    phoneFlag.value = true
                    Text("Введите номер телефона", color = Color.Red, fontSize = 10.sp)
                } else {
                    phoneFlag.value = false
                }
                Spacer(modifier = Modifier.height(20.dp))
                /*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)
                .padding(),
                onClick = {
                    /*viewModel.addAvatar(avatar.value)*/
                    viewModel.CreateUser(surname.value, name.value, phoneNumber.value)
                    navController.navigate("MainPage")
                },
                shape = RoundedCornerShape(23.dp),
                border = BorderStroke(0.dp, Color(0xFFEBEBEB)),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(255,215,0),
                    contentColor = Color.White)
            )
            {
                Text("СОХРАНИТЬ", color = Color.White,
                    modifier = Modifier.padding(),
                    fontSize = 22.sp,
                    fontWeight = FontWeight.Bold,
                    fontFamily = OldStandart)
            }
        }
    }
}

