package com.example.tasks.screens

import EmailViewModel
import RegistrationEvent
import android.util.Patterns
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
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.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.tasks.auxiliary.CustomEmail
import com.example.tasks.auxiliary.CustomPassword
import com.example.tasks.model.User
import com.example.tasks.navigation.Screen
import com.example.tasks.ui.theme.SFPro
import com.google.firebase.Firebase
import com.google.firebase.firestore.firestore

@Composable
fun Entrance(navController: NavController) {
    val fs = Firebase.firestore
    val list = remember {
        mutableStateOf(emptyList<User>())
    }

    val password = remember {
        mutableStateOf("")
    }
    val context = LocalContext.current
    val focusManager = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .pointerInput(Unit) {
                detectTapGestures(onTap = {
                    keyboardController?.hide()
                    focusManager.clearFocus()
                })
            }
            .padding(10.dp),
        horizontalAlignment = Alignment.Start,
        verticalArrangement = Arrangement.Center
    ) {
        val viewModel = viewModel<EmailViewModel>()
        val state = viewModel.state
        Text(
            "Вход по электронной почте",
            fontWeight = FontWeight.Bold,
            fontFamily = SFPro,
            fontSize = 18.sp,
            color = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier.padding(bottom = 20.dp)
        )
        CustomEmail(
            keyboardController = keyboardController,
            focusManager = focusManager,
            search = state.email,
            onValueChange = {
                viewModel.onEvent(RegistrationEvent.EmailChanged(it))
            },
            isError = state.emailError != null
        )
        if (state.emailError != null) {
            Text(text = state.emailError, color = MaterialTheme.colorScheme.error)
        }
        Spacer(modifier = Modifier.height(16.dp))
        CustomPassword("Введите пароль", search = password.value, onValueChange = {
            password.value = it
        }, isError = password.value.isEmpty())
        if (password.value.isEmpty()) {
            Text(text = "Введите пароль", color = MaterialTheme.colorScheme.error)
        }

        if (Patterns.EMAIL_ADDRESS.matcher(state.email).matches() && password.value.isNotEmpty()) {
            Button(
                onClick = {
                    fs.collection("users").whereEqualTo("email", state.email).get()
                        .addOnCompleteListener { it ->
                            if (it.isSuccessful) {
                                list.value = it.result.toObjects(User::class.java)
                                if (list.value.isEmpty()) {
                                    Toast.makeText(
                                        context,
                                        "Вы не зарегистрированы/неверно введена почта",
                                        LENGTH_SHORT
                                    )
                                        .show()
                                } else {
                                    if (list.value.last().password == password.value) {
                                        if (list.value.last().post == "Начальник") {

                                            navController.navigate(
                                                Screen.AppNavigationChief.withArg(
                                                    list.value.last().surname,
                                                    list.value.last().name,
                                                    list.value.last().patronymic,
                                                    list.value.last().division
                                                )
                                            )
                                        } else {
                                            navController.navigate(
                                                Screen.AppNavigationStaff.withArg(
                                                    list.value.last().surname,
                                                    list.value.last().name,
                                                    list.value.last().patronymic
                                                )
                                            )
                                        }
                                    } else {
                                        Toast.makeText(context, "Неверный пароль", LENGTH_SHORT)
                                            .show()
                                        password.value = ""
                                    }
                                }
                            }

                        }

                },

                modifier = Modifier
                    .padding(top = 20.dp)
                    .width(width = 500.dp)
                    .height(height = 56.dp)
                    .testTag("entrance"),
                shape = RoundedCornerShape(size = 10.dp),
                colors = ButtonDefaults.buttonColors(

                    containerColor = Color(0XFF990000),
                    contentColor = Color.White
                )
            ) {
                Text(
                    text = "Войти",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.W900,
                    fontFamily = SFPro
                )
            }
        } else {
            Button(
                modifier = Modifier
                    .padding(top = 20.dp)
                    .width(width = 500.dp)
                    .height(height = 56.dp),
                onClick = { viewModel.onEvent(RegistrationEvent.submit) },
                shape = RoundedCornerShape(size = 10.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFACAAB1),
                    contentColor = Color.White
                )
            ) {
                Text(
                    text = "Войти",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.W900,
                    fontFamily = SFPro
                )
            }

        }


    }

}