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.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
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.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.LocalContext
import androidx.compose.ui.res.stringResource
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.PendingApprovalsStatus
import de.trainingstagebuch.app.viewmodel.PendingApprovalsViewModel

@Composable
fun PendingApprovalsScreen(
    pendingApprovalsViewModel: PendingApprovalsViewModel = viewModel()
) {
    val state by pendingApprovalsViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    LaunchedEffect(state.errorMessage, state.successMessage) {
        state.errorMessage?.let {
            dismissedError = null
            snackbarHostState.showSnackbar(it.resolve(context))
        }
        state.successMessage?.let {
            snackbarHostState.showSnackbar(it.resolve(context))
        }
    }

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

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

            when (state.status) {
                PendingApprovalsStatus.Idle, PendingApprovalsStatus.Loading -> {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator()
                        Text(
                            text = stringResource(R.string.pending_approvals_loading),
                            modifier = Modifier.padding(top = 12.dp)
                        )
                    }
                }

                PendingApprovalsStatus.Error -> {
                    Button(onClick = pendingApprovalsViewModel::load) {
                        Text(stringResource(R.string.home_retry))
                    }
                }

                PendingApprovalsStatus.Success -> {
                    if (state.users.isEmpty()) {
                        Text(
                            text = stringResource(R.string.pending_approvals_empty),
                            style = MaterialTheme.typography.bodyMedium
                        )
                    } else {
                        LazyColumn(modifier = Modifier.fillMaxSize()) {
                            items(state.users, key = { it.id }) { user ->
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 6.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text(text = listOf(user.firstName, user.lastName).joinToString(" ").trim())
                                        if (!user.email.isNullOrBlank()) {
                                            Text(
                                                text = user.email,
                                                style = MaterialTheme.typography.bodySmall
                                            )
                                        }
                                    }
                                    Button(
                                        onClick = { pendingApprovalsViewModel.approveUser(user.id) },
                                        enabled = !state.actionLoading,
                                        modifier = Modifier.padding(end = 6.dp)
                                    ) {
                                        Text(stringResource(R.string.pending_approvals_approve_button))
                                    }
                                    Button(
                                        onClick = { pendingApprovalsViewModel.rejectUser(user.id) },
                                        enabled = !state.actionLoading
                                    ) {
                                        Text(stringResource(R.string.pending_approvals_reject_button))
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
