import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.navigation.NavHostController
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.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
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.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
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.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.lectionsupabase.R
import com.example.lectionsupabase.view.mainActivity.MainViewModel
import androidx.navigation.NavController

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun auth(navHostController: NavHostController, viewModel: MainViewModel) {
    val email = remember { mutableStateOf("") }
    val password = remember { mutableStateOf("") }
    var passwordVisibility by remember { mutableStateOf(false) }
    val montserratSemiBold = FontFamily(Font(R.font.mon_semibold))
    val montserratRegular = FontFamily(Font(R.font.mon_regular))
    val montserratMedium = FontFamily(Font(R.font.mon_medium))
    val loginResult by viewModel.loginResult.observeAsState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFAAD4EE)) // Фон страницы
            .padding(8.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Spacer(modifier = Modifier.height(150.dp))
        Text(
            text = "BenchMap",
            style = TextStyle(
                fontSize = 35.sp,
                fontWeight = FontWeight.SemiBold,
                fontFamily = montserratSemiBold
            ),
            color = Color.White
        )
        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = "Найдите место куда сходить",
            style = TextStyle(
                fontSize = 19.sp,
                fontWeight = FontWeight.Normal,
                fontFamily = montserratRegular
            ),
            color = Color.White,
            modifier = Modifier.padding(bottom = 32.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Box(
            modifier = Modifier
                .size(370.dp, 260.dp) // Размеры формы
                .clip(RoundedCornerShape(12.dp)) // Закругление формы
                .background(Color(0xFFD2E8F6)) // Фон формы
                .padding(26.dp, 30.dp) // Внутренние отступы
        ) {
            Column {
                // Поле ввода Email
                TextField(
                    value = email.value,
                    onValueChange = { email.value = it },
                    label = { Text("Логин", color = Color.White, fontFamily = montserratMedium) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp) // Фиксированная высота для поля
                        .clip(RoundedCornerShape(5.dp)), // Закругление полей
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                    textStyle = TextStyle(fontSize = 17.sp, color = Color.White),
                    colors = TextFieldDefaults.textFieldColors(
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        containerColor = Color(0xFF96C7E5)
                    )
                )
                Spacer(modifier = Modifier.height(16.dp))

                // Поле ввода Password
                TextField(
                    value = password.value,
                    onValueChange = { password.value = it },
                    label = { Text("Пароль", color = Color.White, fontFamily = montserratMedium) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp) // Фиксированная высота для поля
                        .clip(RoundedCornerShape(5.dp)), // Закругление полей
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                    visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
                    trailingIcon = {
                        IconButton(onClick = { passwordVisibility = !passwordVisibility }) {
                            Icon(
                                imageVector = if (passwordVisibility) ImageVector.vectorResource(id = R.drawable.baseline_person_24) else ImageVector.vectorResource(
                                    id = R.drawable.baseline_person_off_24
                                ),
                                tint = Color.Black,
                                contentDescription = if (passwordVisibility) "Скрыть пароль" else "Показать пароль"
                            )
                        }
                    },
                    textStyle = TextStyle(fontSize = 17.sp, color = Color.White),
                    colors = TextFieldDefaults.textFieldColors(
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        containerColor = Color(0xFF96C7E5)
                    )
                )
                Spacer(modifier = Modifier.height(36.dp)) // Увеличенный отступ между полем и кнопкой

                // Кнопка
                Button(
                    onClick = {
                        viewModel.onSignInEmailPassword(
                            email.value,
                            password.value,
                            navHostController
                        )
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(46.dp),
                    shape = RoundedCornerShape(5.dp), // Закругление кнопки
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF7DBCDF),
                        contentColor = Color.White,
                    )
                ) {
                    Text(
                        "Вход",
                        style = TextStyle(
                            fontSize = 18.sp,
                            fontWeight = FontWeight.SemiBold,
                            fontFamily = montserratSemiBold
                        )
                    )
                }
            }
        }

        // Кнопка регистрации вынесена за пределы Box
        Spacer(modifier = Modifier.height(285.dp)) // Отступ перед кнопкой регистрации
        TextButton(
            onClick = {
                navHostController.navigate("reg")
            },
            modifier = Modifier.align(Alignment.CenterHorizontally)
        ) {
            Text(
                text = "Еще нет аккаунта? Зарегистрируйтесь",
                style = TextStyle(
                    fontSize = 17.sp,
                    color = Color.White,
                    fontFamily = montserratMedium
                )
            )
        }
    }
}


