package com.example.shawarma.screens.authorization

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
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.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.example.shawarma.data.sharedpref.PreferencesManager
import com.example.shawarma.ui.theme.JejuFamily
import com.example.shawarma.ui.theme.MyLightRed
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.utils.ScreenPaths
import com.example.shawarma.viewmodels.UserViewModel
import com.example.shawarma.widgets.MyTextField
import com.example.shawarma.widgets.ShawarmaLogo1

@Composable
fun AuthorizationScreen(navHostController: NavHostController) {
    Box(contentAlignment = Alignment.TopCenter){
        ShawarmaLogo1()
        AuthorizationCard(navHostController)
    }
}

@Composable
fun AuthorizationCard(navHostController: NavHostController) {
    val login = remember { mutableStateOf(TextFieldValue("")) }
    val password = remember { mutableStateOf(TextFieldValue("")) }
    val userViewModel: UserViewModel = hiltViewModel<UserViewModel>()
    val preferencesManager = PreferencesManager(LocalContext.current)

    if (userViewModel.token.observeAsState().value != null) {
        preferencesManager.saveData("token", userViewModel.token.value.toString())

        if (login.value.text == "admin") {
            preferencesManager.saveData("user_role", "ADMIN")
        }
        else {
            preferencesManager.saveData("user_role", "USER")
        }

        navHostController.navigate(ScreenPaths.home.name) {
            popUpTo(ScreenPaths.authorization.name) {
                inclusive = true
            }
        }
    }

    if (userViewModel.authorizationState.observeAsState().value == false) {
        AlertDialog(
            title = {
                Text(
                    text = "Ошибка входа в аккаунт",
                    fontFamily = NunitoFamily,
                    fontWeight = FontWeight.Bold,
                    fontSize = 20.sp
                )
            },
            text = {
                Text(
                    text = "Проверьте корректность введенных данных",
                    fontFamily = NunitoFamily,
                    fontWeight = FontWeight.Normal,
                    fontSize = 16.sp
                )
            },
            onDismissRequest = {
                userViewModel.calmAuthorizationState()
            },
            buttons = {
                TextButton(
                    onClick = {
                        userViewModel.calmAuthorizationState()
                    }
                ) {
                    Text("ОК")
                }

            }
        )
    }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .zIndex(2f)
            .verticalScroll(rememberScrollState())
            .imePadding()
            .padding(10.dp)
            .fillMaxHeight()
    ) {
        Card(
            shape = RoundedCornerShape(20.dp),
            modifier = Modifier
                .size(275.dp, 290.dp + 72.dp)
                .padding(top = 72.dp)
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "Авторизация",
                    fontSize = 20.sp,
                    modifier = Modifier.padding(
                        top = 20.dp
                    ),
                    style = TextStyle(
                        fontFamily = JejuFamily
                    )
                )
                MyTextField(
                    text = login,
                    onTextChanged = {login.value = it},
                    modifier = Modifier
                        .padding(
                            top = (20).dp
                        )
                        .size(208.dp, (50).dp),
                    placeholder = "Логин",
                    singleLine = true
                )
                MyTextField(
                    text = password,
                    onTextChanged = {password.value = it},
                    modifier = Modifier
                        .padding(
                            top = (20).dp
                        )
                        .size(208.dp, (50).dp),
                    placeholder = "Пароль",
                    singleLine = true
                )
                Button(
                    onClick = {
                        userViewModel.login(login.value.text, password.value.text)
                    },
                    colors = ButtonDefaults.buttonColors(MyLightRed, Color.White),
                    shape = RoundedCornerShape(20.dp),
                    modifier = Modifier
                        .padding(
                            top = (20).dp
                        )
                        .size(208.dp, (50).dp)
                ) {
                    Text(
                        text = "Войти",
                        style = TextStyle(
                            fontFamily = JejuFamily,
                            fontSize = 16.sp
                        )
                    )
                }
                Button(
                    onClick = {
                              navHostController.navigate(ScreenPaths.registration.name) {
                                  popUpTo(ScreenPaths.registration.name) {
                                      inclusive = true
                                  }
                              }
                    },
                    colors = ButtonDefaults.buttonColors(Color.White),
                    elevation = ButtonDefaults.elevation(0.dp)
                ) {
                    Text(
                        text = "У меня нет аккаунта!",
                        textDecoration = TextDecoration.Underline,
                        style = TextStyle(
                            fontFamily = JejuFamily,
                            fontSize = 12.sp
                        )
                    )
                }
            }
        }
    }
}