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

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imeNestedScroll
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.isImeVisible
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
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.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
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 ru.myitschool.work.R
import ru.myitschool.work.core.TestIds

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun AuthScreen(
    viewModel: AuthViewModel = viewModel(),
    navController: NavController
) {
    val state by viewModel.uiState.collectAsState()
    val isIme = WindowInsets.isImeVisible

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

    BoxWithConstraints {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = if(maxWidth < 400.dp) 48.dp else 200.dp)
                .verticalScroll(rememberScrollState())
                .imePadding()
                .imeNestedScroll(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            when (val currentState = state) {
                is AuthState.Data -> Content(viewModel, currentState, isIme)
                is AuthState.Loading -> {
                    CircularProgressIndicator(
                        modifier = Modifier.size(64.dp)
                    )
                }
            }
        }
    }
}

@Composable
private fun Content(
    viewModel: AuthViewModel,
    state: AuthState.Data,
    isIme: Boolean
) {
    var login by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }


    AnimatedVisibility(!isIme ) {
        Icon(
            painter = painterResource(R.drawable.difference),
            contentDescription = stringResource(R.string.icon_alter),
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(184.dp)
        )
    }

    Spacer(modifier = Modifier.size(48.dp))
    Text(
        text = stringResource(R.string.auth_title_1),
        style = MaterialTheme.typography.headlineLarge,
        textAlign = TextAlign.Center
    )
    Text(
        text = stringResource(R.string.auth_title_2),
        style = MaterialTheme.typography.titleLarge,
        textAlign = TextAlign.Center
    )

    Spacer(modifier = Modifier.size(48.dp))
    OutlinedTextField(
        modifier = Modifier.testTag(TestIds.Auth.CODE_INPUT).fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        value = login,
        onValueChange = {
            login = it
            viewModel.onIntent(AuthIntent.TextInput(login, password))
        },
        placeholder = { Text(stringResource(R.string.auth_placeholder_login)) },
        label = { Text(stringResource(R.string.auth_label_login)) }
    )
    Spacer(modifier = Modifier.size(16.dp))
    OutlinedTextField(
        modifier = Modifier.testTag(TestIds.Auth.CODE_INPUT).fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        value = password,
        onValueChange = {
            password = it
            viewModel.onIntent(AuthIntent.TextInput(login, password))
        },
        placeholder = { Text(stringResource(R.string.auth_placeholder_password)) },
        label = { Text(stringResource(R.string.auth_label_passord)) }
    )
    Spacer(modifier = Modifier.size(16.dp))
    if (state.error != null) {
        Card(
            shape = RoundedCornerShape(20.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.errorContainer,
            ),
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                modifier = Modifier.testTag(TestIds.Auth.ERROR).padding(16.dp),
                text = state.error,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onErrorContainer,
            )
        }

    }
    Spacer(modifier = Modifier.size(20.dp))
    Button(
        modifier = Modifier
            .testTag(TestIds.Auth.SIGN_BUTTON)
            .fillMaxWidth()
            .height(64.dp),
        onClick = {
            viewModel.onIntent(AuthIntent.Send(login, password))
        },
        enabled = state.isEnabledSend,
    ) {
        Text(
            text = stringResource(R.string.auth_sign_in),
            style = MaterialTheme.typography.titleMedium,
        )
    }
}