package llc.arma.ble.app.ui.screen.password

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Visibility
import androidx.compose.material.icons.rounded.VisibilityOff
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
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.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import llc.arma.ble.app.ui.screen.password.view.Loading
import llc.arma.ble.app.ui.screen.password.view.Result
import llc.arma.ble.app.ui.screen.inspection.thermometer.view.LoadingState

@Composable
fun ChangePasswordScreen(
    onNavigationEvent: (ChangePasswordContract.Effect.Navigation) -> Unit
) {

    val viewModel = hiltViewModel<ChangePasswordViewModel>()
    val state = viewModel.viewState.value

    LaunchedEffect("effect"){
        viewModel.effect.onEach {
            when(it){
                is ChangePasswordContract.Effect.Navigation -> onNavigationEvent(it)
            }
        }.launchIn(this)
    }

    Surface(
        shape = RoundedCornerShape(16.dp),
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .padding(24.dp),
    ) {

        Column {

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

            Text(
                modifier = Modifier.fillMaxWidth(),
                style = MaterialTheme.typography.titleLarge,
                text = "Изменение пароля",
                textAlign = TextAlign.Center
            )

            if(state.loading != null){

                when(state.loading){

                    ChangePasswordContract.State.LoadingState.Loading -> {
                        Loading {
                            viewModel.setEvent(it)
                        }
                    }
                    ChangePasswordContract.State.LoadingState.Failure,
                    ChangePasswordContract.State.LoadingState.Success -> {
                        Result(
                            onEvent = {
                                viewModel.setEvent(it)
                            },
                            state = state.loading
                        )
                    }
                }

            } else {

                Column(
                    modifier = Modifier.padding(20.dp)
                ) {


                    var passwordVisibility by remember {
                        mutableStateOf(false)
                    }
                    var rePasswordVisibility by remember {
                        mutableStateOf(false)
                    }

                    @Composable
                    fun TrailingPasswordIcon(
                        visible: Boolean,
                        onClick: () -> Unit
                    ) {
                        IconButton(onClick = onClick) {
                            Icon(
                                contentDescription = null,
                                imageVector = if (visible) {
                                    Icons.Rounded.Visibility
                                } else {
                                    Icons.Rounded.VisibilityOff
                                }
                            )
                        }
                    }

                    val isError = state.exception != null

                    TextField(
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        visualTransformation = if (passwordVisibility.not()) PasswordVisualTransformation() else VisualTransformation.None,
                        value = state.password,
                        onValueChange = {
                            viewModel.setEvent(ChangePasswordContract.Event.OnPasswordChanged(it))
                        },
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.NumberPassword,
                            imeAction = ImeAction.Next),
                        trailingIcon = {
                            TrailingPasswordIcon(visible = passwordVisibility) {
                                passwordVisibility = passwordVisibility.not()
                            }
                        },
                        isError = isError,
                        label = {
                            Text(text = "Пароль")
                        },
                        supportingText = {
                            Row() {
                                Spacer(modifier = Modifier.weight(1f))

                                Text(
                                    style = MaterialTheme.typography.bodyMedium,
                                    text = "${state.password.length}/6"
                                )
                            }
                        }
                    )

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

                    TextField(
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        visualTransformation = if (rePasswordVisibility.not()) PasswordVisualTransformation() else VisualTransformation.None,
                        value = state.rePassword,
                        onValueChange = {
                            viewModel.setEvent(ChangePasswordContract.Event.OnRePasswordChanged(it))
                        },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
                        trailingIcon = {
                            TrailingPasswordIcon(visible = rePasswordVisibility) {
                                rePasswordVisibility = rePasswordVisibility.not()
                            }
                        },
                        label = {
                            Text(text = "Повторите пароль")
                        },
                        isError = isError,
                        supportingText = {

                            Row() {

                                if (isError) {
                                    val text = when (state.exception) {
                                        is ChangePasswordContract.State.ValidationException.WrongLength -> "Неверная длинна"
                                        is ChangePasswordContract.State.ValidationException.PasswordsNotMatch -> "Пароли не совпадают"
                                        null -> ""
                                    }

                                    Text(
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.error,
                                        text = text
                                    )
                                }

                                Spacer(modifier = Modifier.weight(1f))

                                Text(
                                    style = MaterialTheme.typography.bodyMedium,
                                    text = "${state.rePassword.length}/6"
                                )

                            }

                        }
                    )

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

                    Box(
                        modifier = Modifier
                    ) {

                        Surface(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(50.dp),
                            shape = CircleShape,
                            color = MaterialTheme.colorScheme.primaryContainer,
                            onClick = {
                                viewModel.setEvent(ChangePasswordContract.Event.OnChange)
                            }
                        ) {

                            Box(modifier = Modifier.fillMaxSize()) {

                                Text(
                                    modifier = Modifier.align(Alignment.Center),
                                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                                    style = MaterialTheme.typography.labelLarge,
                                    text = "Применить"
                                )

                            }

                        }

                    }

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

                    Box(
                        modifier = Modifier
                    ) {

                        Surface(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(50.dp),
                            shape = CircleShape,
                            color = MaterialTheme.colorScheme.surfaceVariant,
                            onClick = {
                                viewModel.setEvent(ChangePasswordContract.Event.OnNavigateUp)
                            }
                        ) {

                            Box(modifier = Modifier.fillMaxSize()) {

                                Text(
                                    modifier = Modifier.align(Alignment.Center),
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    style = MaterialTheme.typography.labelLarge,
                                    text = "Отменить"
                                )

                            }

                        }

                    }

                }

            }

        }

    }

}