package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
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.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.MyTischtennisAccountViewModel
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

@Composable
fun MyTischtennisAccountScreen(
    viewModel: MyTischtennisAccountViewModel = viewModel()
) {
    val state by viewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(state.errorMessage, state.successMessage) {
        val message = state.errorMessage ?: state.successMessage ?: return@LaunchedEffect
        snackbarHostState.showSnackbar(message.resolve(context))
    }

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.mytischtennis_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Text(
                text = stringResource(R.string.mytischtennis_title),
                style = MaterialTheme.typography.headlineSmall
            )

            state.errorMessage?.let {
                ErrorBanner(
                    message = it.resolve(context),
                    onDismiss = viewModel::clearMessages
                )
            }

            if (state.loading) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator()
                }
            } else {
                val account = state.account
                if (account == null) {
                    Text(text = stringResource(R.string.mytischtennis_no_account))
                } else {
                    Text(text = stringResource(R.string.mytischtennis_email_value, account.email))
                    Text(
                        text = stringResource(
                            R.string.mytischtennis_password_saved_value,
                            if (state.status?.hasPassword == true) {
                                stringResource(R.string.common_yes)
                            } else {
                                stringResource(R.string.common_no)
                            }
                        )
                    )
                    account.clubId?.let { clubId ->
                        Text(
                            text = stringResource(
                                R.string.mytischtennis_club_value,
                                account.clubName.orEmpty(),
                                clubId,
                                account.fedNickname.orEmpty()
                            )
                        )
                    }
                    account.lastLoginSuccess?.let {
                        Text(text = stringResource(R.string.mytischtennis_last_login_success_value, formatDate(it)))
                    }
                    account.lastLoginAttempt?.let {
                        Text(text = stringResource(R.string.mytischtennis_last_login_attempt_value, formatDate(it)))
                    }
                }

                OutlinedTextField(
                    value = state.formEmail,
                    onValueChange = viewModel::onEmailChanged,
                    label = { Text(stringResource(R.string.mytischtennis_email_label)) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )
                OutlinedTextField(
                    value = state.formPassword,
                    onValueChange = viewModel::onPasswordChanged,
                    label = { Text(stringResource(R.string.mytischtennis_password_label)) },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true
                )

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(onClick = viewModel::saveAccount, enabled = !state.saving && !state.loading) {
                        if (state.saving) {
                            CircularProgressIndicator(modifier = Modifier.padding(vertical = 2.dp), strokeWidth = 2.dp)
                        } else {
                            Text(stringResource(R.string.mytischtennis_save_account))
                        }
                    }
                    Button(onClick = viewModel::verifyLogin, enabled = !state.verifying && !state.loading) {
                        if (state.verifying) {
                            CircularProgressIndicator(modifier = Modifier.padding(vertical = 2.dp), strokeWidth = 2.dp)
                        } else {
                            Text(stringResource(R.string.mytischtennis_verify_login))
                        }
                    }
                }

                Button(
                    onClick = viewModel::unlinkAccount,
                    enabled = !state.deleting && !state.loading,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    if (state.deleting) {
                        CircularProgressIndicator(modifier = Modifier.padding(vertical = 2.dp), strokeWidth = 2.dp)
                    } else {
                        Text(stringResource(R.string.mytischtennis_unlink_account))
                    }
                }

                Text(
                    text = stringResource(R.string.mytischtennis_info_block),
                    style = MaterialTheme.typography.bodySmall
                )
            }
        }
    }
}

private fun formatDate(value: String): String {
    return runCatching {
        OffsetDateTime.parse(value).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"))
    }.getOrElse { value }
}
