package com.zyzf.coffeepreorder.ui.register


import android.content.res.Configuration
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.Add
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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 coil.compose.AsyncImage
import coil.request.ImageRequest
import com.zyzf.coffeepreorder.CoffeeApplication
import com.zyzf.coffeepreorder.R
import com.zyzf.coffeepreorder.database.model.User
import com.zyzf.coffeepreorder.ui.AppViewModelProvider
import com.zyzf.coffeepreorder.ui.navigation.Screen
import com.zyzf.coffeepreorder.ui.theme.CoffeePreorderTheme
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun Register(
    navController: NavController?,
    viewModel: RegisterViewModel = viewModel(factory = AppViewModelProvider.Factory)
    ) {
    val coroutineScope = rememberCoroutineScope()
    var login: String by remember { mutableStateOf("") }
    var fio: String by remember { mutableStateOf("") }
    var phone: String by remember { mutableStateOf("") }
    var password: String by remember { mutableStateOf("") }
    var confPassword: String by remember { mutableStateOf("") }
    Column(Modifier.padding(all = 10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
        AsyncImage(
            model = ImageRequest.Builder(context = LocalContext.current).data("https://zyzf.space/s/YsHjPo3NDmoptSk/download/coffee_image.png")
                .crossfade(true).build(),
            error = painterResource(R.drawable.ic_broken_image),
            placeholder = painterResource(R.drawable.loading_img),
            contentDescription = "Кофе",
            contentScale = ContentScale.Crop,
            modifier = Modifier.size(150.dp)
        )
        Spacer(modifier = Modifier.padding(all = 20.dp))
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = login, onValueChange = {login = it},
            label = {
                Text(stringResource(id = R.string.profile_login_label))
            }
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = fio, onValueChange = {fio = it},
            label = {
                Text(stringResource(id = R.string.profile_fio_label))
            }
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = phone, onValueChange = {phone = it},
            label = {
                Text(stringResource(id = R.string.profile_phone_label))
            }
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = password, onValueChange = {password = it},
            label = {
                Text(stringResource(id = R.string.profile_passw_label))
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = PasswordVisualTransformation()
        )
        OutlinedTextField(modifier = Modifier.fillMaxWidth(),
            value = confPassword, onValueChange = {confPassword = 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 = {
                var user: User?
                coroutineScope.launch (Dispatchers.Main) {
                    if (password == confPassword) {
                        user = viewModel.register(User(login, fio, phone, password, "user"))
                        if (user != null) {
                            CoffeeApplication.currentUser = null
                            CoffeeApplication.currentUser = user!!
                            navController?.navigate(Screen.CoffeeList.route)
                        } else {
                            password = ""
                            login = "Неверный логин или пароль"
                        }
                    } else {
                        password = ""
                        confPassword = ""
                        login = "Пароль не совпадает с подтверждением пароля"
                    }
                }
            },
            shape = CircleShape,
            modifier = Modifier.fillMaxWidth(fraction = 0.75f),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                contentColor = MaterialTheme.colorScheme.primary
            )
        ) {
            Icon(
                imageVector = Icons.Default.Add,
                contentDescription = "Favorite",
                modifier = Modifier.size(20.dp)
            )
            Spacer(Modifier.size(ButtonDefaults.IconSpacing))
            Text(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 RegisterPreview() {
    CoffeePreorderTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            Register(null)
        }
    }
}