package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.platform.LocalContext
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.unit.dp
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import de.trainingstagebuch.app.R
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.viewmodel.LoginStatus
import de.trainingstagebuch.app.viewmodel.LoginViewModel

@Composable
fun LoginScreen(
    onLoginSuccess: () -> Unit,
    onNavigateToRegister: () -> Unit,
    onNavigateToForgotPassword: () -> Unit,
    loginViewModel: LoginViewModel = viewModel()
) {
    val state by loginViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    LaunchedEffect(state.status) {
        if (state.status == LoginStatus.Success) {
            onLoginSuccess()
            loginViewModel.resetToIdle()
        }
    }

    LaunchedEffect(state.errorMessage) {
        val error = state.errorMessage
        if (error != null) {
            dismissedError = null
            snackbarHostState.showSnackbar(error.resolve(context))
        }
    }

    Scaffold(
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(24.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = stringResource(R.string.auth_login_title),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 20.dp)
            )

            OutlinedTextField(
                value = state.email,
                onValueChange = loginViewModel::onEmailChanged,
                label = { Text(stringResource(R.string.auth_email_label)) },
                keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                    keyboardType = KeyboardType.Email,
                    imeAction = ImeAction.Next
                ),
                singleLine = true,
                enabled = state.status != LoginStatus.Loading,
                modifier = Modifier.fillMaxWidth()
            )

            OutlinedTextField(
                value = state.password,
                onValueChange = loginViewModel::onPasswordChanged,
                label = { Text(stringResource(R.string.auth_password_label)) },
                visualTransformation = PasswordVisualTransformation(),
                keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                    keyboardType = KeyboardType.Password,
                    imeAction = ImeAction.Done
                ),
                singleLine = true,
                enabled = state.status != LoginStatus.Loading,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 12.dp)
            )

            val currentError = state.errorMessage
            if (currentError != null && currentError != dismissedError) {
                ErrorBanner(
                    message = currentError.resolve(context),
                    onDismiss = { dismissedError = currentError },
                    modifier = Modifier.padding(top = 10.dp)
                )
            }

            Button(
                onClick = loginViewModel::login,
                enabled = state.status != LoginStatus.Loading,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                if (state.status == LoginStatus.Loading) {
                    CircularProgressIndicator(
                        strokeWidth = 2.dp,
                        modifier = Modifier.padding(vertical = 2.dp)
                    )
                } else {
                    Text(stringResource(R.string.auth_login_button))
                }
            }

            TextButton(
                onClick = onNavigateToRegister,
                enabled = state.status != LoginStatus.Loading,
                modifier = Modifier.padding(top = 8.dp)
            ) {
                Text(stringResource(R.string.auth_login_to_register))
            }

            TextButton(
                onClick = onNavigateToForgotPassword,
                enabled = state.status != LoginStatus.Loading,
                modifier = Modifier.padding(top = 4.dp)
            ) {
                Text(stringResource(R.string.auth_forgot_link))
            }
        }
    }
}
