package ru.myitschool.work.ui.screen.auth

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
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.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import ru.myitschool.work.R
import ru.myitschool.work.core.TestIds
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.material3.OutlinedTextField
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.sp

@Composable
fun AuthScreen(
    viewModel: AuthViewModel = viewModel(),
    navController: NavController
) {
    val state by viewModel.uiState.collectAsState()


    LaunchedEffect(Unit) {
        viewModel.actionFlow.collect { action ->
            when (action) {
                is AuthAction.Open -> navController.navigate(action.destination) {
                    popUpTo(0)
                }
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(all = 44.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {

        when (val currentState = state) {
            is AuthState.Data -> Content(viewModel, currentState)
            is AuthState.Loading -> {
                CircularProgressIndicator(
                    modifier = Modifier.size(64.dp)
                )
            }
        }
    }
}

@Composable
private fun Content(
    viewModel: AuthViewModel,
    state: AuthState.Data
) {
    var inputLogin by rememberSaveable { mutableStateOf("") }
    val googleSans = FontFamily(
        Font(R.font.googlesans_regular, FontWeight.Medium, FontStyle.Normal)
    )
    Spacer(modifier = Modifier.size(0.dp))
    Text(
        text = stringResource(R.string.auth_title),
        fontFamily = googleSans,
        color = Color(0xFF284777),
        fontSize = 35.sp,
        textAlign = TextAlign.Center,
        fontWeight = FontWeight.Medium,
        fontStyle = FontStyle.Normal,
        modifier = Modifier.fillMaxWidth(1f)
    )
    Spacer(modifier = Modifier.size(106.dp))
    Text(
        text = stringResource(R.string.auth_label_login),
        fontFamily = googleSans,
        color = Color(0xFF74777f),
        textAlign = TextAlign.Start,
        fontWeight = FontWeight.Medium,
        fontStyle = FontStyle.Normal,
        modifier = Modifier.fillMaxWidth(1f)
    )
    Spacer(modifier = Modifier.size(10.dp))
    OutlinedTextField(
        modifier = Modifier.testTag(TestIds.Auth.LOGIN_INPUT).fillMaxWidth(),
        value = inputLogin,
        shape = RoundedCornerShape(12.dp),
        colors = TextFieldDefaults.colors(unfocusedContainerColor = Color(0xFFededf4)),
        onValueChange = {
            inputLogin = it
            viewModel.onIntent(AuthIntent.TextInput(
                it,
                textPassword = ""
            ))
        }
    )
    var inputPassword by rememberSaveable { mutableStateOf("") }
    Spacer(modifier = Modifier.size(20.dp))
    Text(
        text = stringResource(R.string.auth_label_password),
        fontFamily = googleSans,
        color = Color(0xFF74777f),
        textAlign = TextAlign.Start,
        fontWeight = FontWeight.Medium,
        fontStyle = FontStyle.Normal,
        modifier = Modifier.fillMaxWidth(1f)
    )
    Spacer(modifier = Modifier.size(10.dp))
    OutlinedTextField(
        modifier = Modifier.testTag(TestIds.Auth.PASSWORD_INPUT).fillMaxWidth(),
        value = inputPassword,
        shape = RoundedCornerShape(12.dp),
        colors = TextFieldDefaults.colors(unfocusedContainerColor = Color(0xFFededf4)),
        onValueChange = {
            inputPassword = it
            viewModel.onIntent(AuthIntent.TextInput(
                inputLogin,
                textPassword = it
            ))
        }
    )
    Spacer(modifier = Modifier.size(35.dp))
    Button(
        modifier = Modifier.testTag(TestIds.Auth.SIGN_BUTTON).fillMaxWidth(),
        onClick = {
            viewModel.onIntent(AuthIntent.Send(inputLogin, inputPassword))
        },
        enabled = state.isEnabledSend
    ) {
        Text(
            text = "Войти",
            modifier = Modifier.padding(10.dp),
            fontFamily = googleSans,
            fontWeight = FontWeight.Medium,
            fontStyle = FontStyle.Normal,
            fontSize = 18.sp
        )
    }
    if (state.error != null) {
        Text(
            modifier = Modifier.testTag(TestIds.Auth.ERROR),
            text = if (viewModel.incorrectAttemptNum > 5) {
                "Превышен лимит попыток входа"
            } else {
                state.error
            },
            style = MaterialTheme.typography.bodyMedium,
            color = Color.Red,
        )
    }
}

@Preview
@Composable
fun AuthView() {
    AuthScreen(navController = rememberNavController())
}