package com.example.myapplication.ui.list

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.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.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.R
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.room.model.user.User
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.database.room.viewmodel.user.EntryUserViewModel
import com.example.myapplication.database.room.viewmodel.user.RegisterUserViewModel
import com.example.myapplication.ui.navigation.Screen
import com.example.myapplication.setting.DataStoreManager
import com.example.myapplication.setting.SettingData
import kotlinx.coroutines.launch

@SuppressLint("UnrememberedMutableState")
@Composable
fun UserList(
    navController: NavController?,
    isDarkTheme: MutableState<Boolean>,
    dataStoreManager: DataStoreManager,
    registerUserViewModel: RegisterUserViewModel = viewModel(factory = AppViewModelProvider.Factory),
    entryUserViewModel: EntryUserViewModel = viewModel(factory = AppViewModelProvider.Factory),
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val context = LocalContext.current

    var errorState by remember { mutableStateOf<String?>(null) }

    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var isRegistration by remember { mutableStateOf(false) }
    var isAuto by remember { mutableStateOf(false) }
    var isPasswordVisible by remember { mutableStateOf(false) }

    var isCardVisible by remember { mutableStateOf(false) }

    val coroutineScope = rememberCoroutineScope()

    registerUserViewModel.setUserList()
    var users = mutableStateOf<List<User>>(emptyList())
    registerUserViewModel.users.observeForever { userList ->
        users.value = userList
    }

    entryUserViewModel.setUserList()
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }

    if (getUser?.uid != null) {
        LoginScreenProfile(currentUserViewModel, navController)
    } else {

        LazyColumn {
            item(key = isAuto) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = "Логин",
                        modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                    BasicTextField(
                        value = username,
                        textStyle = TextStyle(color = MaterialTheme.colorScheme.background),
                        onValueChange = { newValue -> username = newValue },
                        modifier = Modifier
                            .fillMaxWidth()
                            .size(36.dp)
                            .background(
                                MaterialTheme.colorScheme.onBackground,
                                RoundedCornerShape(18.dp)
                            )
                            .padding(start = 13.dp, top = 8.dp)
                    )

                    Text(
                        text = "Пароль",
                        modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                    BasicTextField(
                        value = password,
                        textStyle = TextStyle(color = MaterialTheme.colorScheme.background),
                        onValueChange = { newValue -> password = newValue },
                        modifier = Modifier
                            .fillMaxWidth()
                            .size(36.dp)
                            .background(
                                MaterialTheme.colorScheme.onBackground,
                                RoundedCornerShape(18.dp)
                            )
                            .padding(start = 13.dp, top = 8.dp),
                        visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation()

                    )

                    if (isRegistration) {
                        Button(
                            onClick = {
                                coroutineScope.launch {
                                    val registrationSuccessful = registerUserViewModel.registerUser(username, password)
                                    if (registrationSuccessful) {
                                        navController?.navigate(Screen.LoginScreen.route)
                                    } else {
                                        Log.d("Регистрация","Ошибка")
                                        // При других ошибках регистрации выводим сообщение
                                        errorState = "Пользователь с таким логином уже существует"
                                    }

                                }
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp)
                        ) {
                            Text("Регистрация")
                        }

                        Text(
                            text = "Войти",
                            modifier = Modifier
                                .clickable {
                                    isRegistration = false
                                }
                                .align(Alignment.CenterHorizontally),
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    } else {
                        Button(
                            onClick = {
                                val user = entryUserViewModel.loginUser(username, password)
                                if (user != null) {
                                    currentUserViewModel.setArgument(user.uid.toString())
                                    navController?.navigate(Screen.LoginScreen.route)
                                } else {
                                    // При ошибке авторизации выводим сообщение
                                    errorState = "Ошибка авторизации: неверный логин или пароль"
                                }
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp)
                        ) {
                            Text("Вход")
                        }

                        Text(
                            text = "Зарегистрироваться",
                            modifier = Modifier
                                .clickable {
                                    isRegistration = true
                                }
                                .align(Alignment.CenterHorizontally),
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                    errorState?.let { errorMessage ->
                        AlertDialog(
                            onDismissRequest = { errorState = null },
                            title = { Text(text = "Ошибка") },
                            text = { Text(errorMessage, color = MaterialTheme.colorScheme.onBackground) },
                            buttons = {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(8.dp),
                                    horizontalArrangement = Arrangement.End
                                ) {
                                    TextButton(onClick = { errorState = null }) {
                                        Text("Закрыть", color = MaterialTheme.colorScheme.onBackground)
                                    }
                                }
                            },
                            modifier = Modifier.padding(16.dp),
                            backgroundColor = MaterialTheme.colorScheme.background,
                            contentColor = MaterialTheme.colorScheme.onBackground
                        )
                    }
                    val switchColors = SwitchDefaults.colors(
                        checkedThumbColor = MaterialTheme.colorScheme.primary, // Change the color when the switch is checked
                        checkedTrackColor = MaterialTheme.colorScheme.secondary,  // Change the color of the track when the switch is checked
                        uncheckedThumbColor = MaterialTheme.colorScheme.primary, // Change the color when the switch is unchecked
                        uncheckedTrackColor = MaterialTheme.colorScheme.onPrimary // Change the color of the track when the switch is unchecked
                    )
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                    ) {
                        // Заголовок
                        Text(
                            text = "Настройки",
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { isCardVisible = !isCardVisible }
                                .padding(16.dp),
                            textAlign = TextAlign.Center,
                            color = MaterialTheme.colorScheme.onSurface
                        )

                        // Анимированная видимость Card
                        AnimatedVisibility(visible = isCardVisible) {
                            Card(
                                border = BorderStroke(2.dp, MaterialTheme.colorScheme.onBackground),
                                modifier = Modifier
                                    .background(MaterialTheme.colorScheme.background)
                                    .fillMaxWidth()
                                    .padding(16.dp)
                            ) {
                                Column(
                                    modifier = Modifier
                                        .background(MaterialTheme.colorScheme.background)
                                        .fillMaxWidth()
                                        .padding(16.dp),
                                    verticalArrangement = Arrangement.Center
                                ) {

                                    Text(
                                        "Темная тема",
                                        modifier = Modifier
                                            .align(Alignment.CenterHorizontally)
                                            .padding(5.dp),
                                        color = MaterialTheme.colorScheme.onSurface
                                    )

                                    val coroutine = rememberCoroutineScope()

                                    Switch(
                                        checked = isDarkTheme.value,
                                        onCheckedChange = {
                                            isDarkTheme.value = !isDarkTheme.value
                                            coroutine.launch {
                                                dataStoreManager.saveSettings(
                                                    SettingData(
                                                        isDarkTheme = isDarkTheme.value
                                                    )
                                                )
                                            }
                                        },
                                        colors = switchColors,
                                        modifier = Modifier
                                            .align(Alignment.CenterHorizontally)
                                            .padding(5.dp)
                                    )

                                    Text(
                                        "Показывать содержимое пароля",
                                        modifier = Modifier
                                            .align(Alignment.CenterHorizontally)
                                            .padding(5.dp),
                                        color = MaterialTheme.colorScheme.onSurface
                                    )

                                    Switch(
                                        checked = isPasswordVisible,
                                        onCheckedChange = { isPasswordVisible = it },
                                        colors = switchColors,
                                        modifier = Modifier
                                            .align(Alignment.CenterHorizontally)
                                            .padding(5.dp)
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun LoginScreen(navController: NavController?) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text("Соедение с ЛК УлГТУ произошло успешно.", fontWeight = FontWeight.Bold)
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            "Для дальнейшей работы, нажмите кнопку \"Готово\".",
            textAlign = TextAlign.Center
        )
        Button(
            onClick = {
                Log.d("Кнопка", "Тык")
                navController?.navigate(Screen.BikeList.route)
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
        ) {
            Text("Готово")
        }
    }
}

@Composable
fun LoginScreenProfile(currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory), navController: NavController?) {
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }
    val coroutineScope = rememberCoroutineScope()
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = null,
            modifier = Modifier
                .size(120.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.primary)
        )

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = "Вы авторизованы под аккаунтом: ${getUser?.login}",
            textAlign = TextAlign.Center
        )
        Spacer(modifier = Modifier.height(16.dp))
        if(getUser?.role == "admin") {
            Button(
                onClick = {
                    coroutineScope.launch {
                        navController?.navigate(Screen.Report.route)
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
            ) {
                Text("Сформировать отчет")
            }
        }

        Button(
            onClick = {
                // Perform logout action
                currentUserViewModel.setNullUser()
                navController?.navigate(Screen.LoginScreen.route)
                // Navigate back to the login screen
                //navController?.popBackStack()
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
        ) {
            Text("Выйти")
        }
    }
}

