package com.zyzf.coffeepreorder.ui.profile

import android.content.res.Configuration
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Create
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.outlined.Clear
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.zyzf.coffeepreorder.CoffeeApplication
import com.zyzf.coffeepreorder.R
import com.zyzf.coffeepreorder.database.AppDatabase
import com.zyzf.coffeepreorder.database.model.User
import com.zyzf.coffeepreorder.ui.AppViewModelProvider
import com.zyzf.coffeepreorder.ui.login.LoginViewModel
import com.zyzf.coffeepreorder.ui.navigation.Screen
import com.zyzf.coffeepreorder.ui.theme.CoffeePreorderTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@OptIn(DelicateCoroutinesApi::class)
@Composable
fun Profile(
    navController: NavController?,
    viewModel: ProfileViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val openDialogEdit = remember { mutableStateOf(false) }
    val openDialogExit = remember { mutableStateOf(false) }
    val openDialogDelete = remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current
    var user: User by remember { mutableStateOf(User("", "", "", "", "")) }
    var userLogin by remember { mutableStateOf("") }
    var userFIO by remember { mutableStateOf("") }
    var userPhone by remember { mutableStateOf("") }
    val userOldPsswd = remember { mutableStateOf("") }
    val userNewPsswd = remember { mutableStateOf("") }
    val userNewPsswdConf = remember { mutableStateOf("") }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            user = CoffeeApplication.currentUser!!
            userLogin = user.login
            userFIO = user.fio
            userPhone = user.phone
        }
    }
    Column(Modifier.padding(all = 10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = userLogin, onValueChange = {userLogin = it},
            label = {
                Text(stringResource(id = R.string.profile_login_label))
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = userFIO, onValueChange = {userFIO = it},
            label = {
                Text(stringResource(id = R.string.profile_fio_label))
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = userPhone, onValueChange = {userPhone = it},
            label = {
                Text(stringResource(id = R.string.profile_phone_label))
            }
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = userOldPsswd.value, onValueChange = {userOldPsswd.value = it},
            label = {
                Text(stringResource(id = R.string.profile_oldpassw_label))
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = PasswordVisualTransformation()
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = userNewPsswd.value, onValueChange = {userNewPsswd.value = it},
            label = {
                Text(stringResource(id = R.string.profile_newpassw_label))
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = PasswordVisualTransformation()
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = userNewPsswdConf.value, onValueChange = {userNewPsswdConf.value = it},
            label = {
                Text(stringResource(id = R.string.profile_confpassw_label))
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = PasswordVisualTransformation()
        )
        Spacer(modifier = Modifier.padding(all = 20.dp))
        Button(
            onClick = { openDialogEdit.value = true },
            shape = CircleShape,
            modifier = Modifier.fillMaxWidth(fraction = 0.75f),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                contentColor = MaterialTheme.colorScheme.primary
            )
        ) {
            // Inner content including an icon and a text label
            Icon(
                imageVector = Icons.Default.Create,
                contentDescription = "Favorite",
                modifier = Modifier.size(20.dp)
            )
            Spacer(Modifier.size(ButtonDefaults.IconSpacing))
            Text(text = "Редактировать")
        }
        Button(
            onClick = { openDialogExit.value = true },
            shape = CircleShape,
            modifier = Modifier.fillMaxWidth(fraction = 0.75f),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.errorContainer,
                contentColor = MaterialTheme.colorScheme.error
            )
        ) {
            // Inner content including an icon and a text label
            Icon(
                imageVector = Icons.Default.Close,
                contentDescription = "Favorite",
                modifier = Modifier.size(20.dp)
            )
            Spacer(Modifier.size(ButtonDefaults.IconSpacing))
            Text(text = "Выход")
        }
        OutlinedButton(
            onClick = { openDialogDelete.value = true },
            shape = CircleShape,
            modifier = Modifier.fillMaxWidth(fraction = 0.75f),
            border= BorderStroke(1.dp, MaterialTheme.colorScheme.error),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.Transparent,
                contentColor = MaterialTheme.colorScheme.error
            )
        ) {
            // Inner content including an icon and a text label
            Icon(
                imageVector = Icons.Outlined.Clear,
                contentDescription = "Удалить",
                modifier = Modifier.size(20.dp)
            )
            Spacer(Modifier.size(ButtonDefaults.IconSpacing))
            Text(text = "Удалить аккаунт")
        }
    }
    if (openDialogEdit.value) {
        AlertDialog(
            icon = {
                Icon(Icons.Default.Edit, contentDescription = "Example Icon")
            },
            title = {
                Text(text = "Подтверждение")
            },
            text = {
                Text(text = "Вы хотите применить изменения?")
            },
            onDismissRequest = {
                openDialogEdit.value = false
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        coroutineScope.launch {
                            val user: User = viewModel.changeUser(user.password, userOldPsswd.value, userNewPsswd.value, userNewPsswd.value,
                                user.uid, userLogin, userFIO, userPhone, user.role)
                            CoffeeApplication.currentUser = user
                        }
                        openDialogEdit.value = false
                    }
                ) {
                    Text("Да")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialogEdit.value = false
                    }
                ) {
                    Text("Нет")
                }
            }
        )
    }
    if (openDialogExit.value) {
        AlertDialog(
            icon = {
                Icon(Icons.Default.Close, contentDescription = "Example Icon")
            },
            title = {
                Text(text = "Подтверждение")
            },
            text = {
                Text(text = "Вы хотите выйти из аккаунта?")
            },
            onDismissRequest = {
                openDialogExit.value = false
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        GlobalScope.launch (Dispatchers.Main) {
                            CoffeeApplication.currentUser = null
                        }
                        openDialogExit.value = false
                        navController?.navigate(Screen.Login.route)
                    }
                ) {
                    Text("Да")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialogExit.value = false
                    }
                ) {
                    Text("Нет")
                }
            }
        )
    }
    if (openDialogDelete.value) {
        AlertDialog(
            icon = {
                Icon(Icons.Default.Close, contentDescription = "Example Icon")
            },
            title = {
                Text(text = "Подтверждение")
            },
            text = {
                Text(text = "Вы хотите удалить аккаунт?")
            },
            onDismissRequest = {
                openDialogDelete.value = false
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        GlobalScope.launch (Dispatchers.Main) {
                            CoffeeApplication.currentUser = null
                            AppDatabase.getInstance(context).userDao().delete(user)
                        }
                        openDialogDelete.value = false
                        navController?.navigate(Screen.Login.route)
                    }
                ) {
                    Text("Да")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialogDelete.value = false
                    }
                ) {
                    Text("Нет")
                }
            }
        )
    }
}

@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun ProfilePreview() {
    CoffeePreorderTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            Profile(null)
        }
    }
}