package io.nexilis.alpha.ui.main

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import io.nexilis.alpha.ui.viewmodel.MainViewModel
import io.nexilis.service.core.getSharedPreferences
import io.nexilis.service.core.optString
import io.nexilis.service.core.put
import io.nexilis.service.data.viewmodels.BuddyViewModel

@Composable
fun SignUp(
    navController: NavHostController,
    mainViewModel: MainViewModel = hiltViewModel(),
    completion: (Boolean) -> Unit
) {
    SideEffect {
        mainViewModel.setTitle("Sign Up")
    }
    var textUsername by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue("", TextRange(0, 7)))
    }
    var textPassword by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue("", TextRange(0, 7)))
    }
    var textConfirmPassword by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue("", TextRange(0, 7)))
    }
    var isVisiblePassword by remember {
        mutableStateOf(false)
    }
    var isVisibleConfirmPassword by remember {
        mutableStateOf(false)
    }
    val viewModel: BuddyViewModel = hiltViewModel()
    val context = LocalContext.current
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(start = 16.dp, end = 16.dp)
            .verticalScroll(
                rememberScrollState()
            ),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .imePadding(),
            value = textUsername,
            onValueChange = { textUsername = it },
            label = {
                Text(text = "Username")
            },
            maxLines = 1
        )
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .imePadding(),
            value = textPassword,
            onValueChange = { textPassword = it },
            label = {
                Text(text = "Password")
            },
            visualTransformation = if (isVisiblePassword) VisualTransformation.None
            else PasswordVisualTransformation(),
            trailingIcon = {
                IconButton(onClick = { isVisiblePassword = !isVisiblePassword }) {
                    Icon(
                        imageVector = if (isVisiblePassword) Icons.Default.Visibility
                        else Icons.Default.VisibilityOff,
                        contentDescription = ""
                    )
                }
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            maxLines = 1
        )
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .imePadding(),
            value = textConfirmPassword,
            onValueChange = { textConfirmPassword = it },
            label = {
                Text(text = "Confirm password")
            },
            visualTransformation = if (isVisibleConfirmPassword) VisualTransformation.None
            else PasswordVisualTransformation(),
            trailingIcon = {
                IconButton(onClick = { isVisibleConfirmPassword = !isVisibleConfirmPassword }) {
                    Icon(
                        imageVector = if (isVisibleConfirmPassword) Icons.Default.Visibility
                        else Icons.Default.VisibilityOff,
                        contentDescription = ""
                    )
                }
            },
            maxLines = 1
        )
        Spacer(modifier = Modifier.size(8.dp))
        Button(onClick = {
            viewModel.signUp(
                textUsername.text,
                textConfirmPassword.text
            ) { r, pin ->
                completion(r)
                if (r && pin.isNotEmpty()) {
                    context.getSharedPreferences().put(key = "pin", value = pin)
                }
            }
        }) {
            Text(text = "Submit")
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SignIn(navController: NavHostController, completion: (Boolean) -> Unit) {
    val viewModel: BuddyViewModel = hiltViewModel()
    var textUsername by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue("", TextRange(0, 7)))
    }
    var textPassword by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue("", TextRange(0, 7)))
    }
    var isVisiblePassword by remember {
        mutableStateOf(false)
    }
    val context = LocalContext.current
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .imePadding(),
            value = textUsername,
            onValueChange = { textUsername = it },
            label = {
                Text(text = "Username")
            },
            maxLines = 1
        )
        OutlinedTextField(
            modifier = Modifier
                .fillMaxWidth()
                .imePadding(),
            value = textPassword,
            onValueChange = { textPassword = it },
            label = {
                Text(text = "Password")
            },
            visualTransformation = if (isVisiblePassword) VisualTransformation.None
            else PasswordVisualTransformation(),
            trailingIcon = {
                IconButton(onClick = { isVisiblePassword = !isVisiblePassword }) {
                    Icon(
                        imageVector = if (isVisiblePassword) Icons.Default.Visibility
                        else Icons.Default.VisibilityOff,
                        contentDescription = ""
                    )
                }
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            maxLines = 1
        )
        Spacer(modifier = Modifier.size(8.dp))
        Button(onClick = {
            val api = context.getSharedPreferences().optString("api", "")
            viewModel.signIn(api, textUsername.text, textPassword.text) { r, pin ->
                completion(r)
                if (r && pin.isNotEmpty()) {
                    context.getSharedPreferences().put(key = "pin", value = pin)
                }
            }
        }) {
            Text(text = "Submit")
        }
    }
}