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.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.ShowClubStatus
import de.trainingstagebuch.app.viewmodel.ShowClubViewModel

@Composable
fun ShowClubScreen(
    clubId: String,
    showClubViewModel: ShowClubViewModel = viewModel()
) {
    val state by showClubViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    LaunchedEffect(clubId) {
        showClubViewModel.load(clubId)
    }

    LaunchedEffect(state.errorMessage, state.status) {
        val error = state.errorMessage
        if (state.status == ShowClubStatus.Error && error != null) {
            dismissedError = null
            snackbarHostState.showSnackbar(error.resolve(context))
        }
    }

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.app_name)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            when (state.status) {
                ShowClubStatus.Idle, ShowClubStatus.Loading -> {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator()
                        Text(
                            text = stringResource(R.string.show_club_loading),
                            modifier = Modifier.padding(top = 12.dp)
                        )
                    }
                }

                ShowClubStatus.Error -> {
                    val currentError = state.errorMessage
                    if (currentError != null && currentError != dismissedError) {
                        ErrorBanner(
                            message = currentError.resolve(context),
                            onDismiss = { dismissedError = currentError },
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                    Button(
                        onClick = { showClubViewModel.load(clubId) },
                        modifier = Modifier.padding(top = 12.dp)
                    ) {
                        Text(stringResource(R.string.home_retry))
                    }
                }

                ShowClubStatus.AccessDenied -> {
                    Text(
                        text = stringResource(R.string.show_club_no_access),
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    if (state.accessRequested) {
                        Text(
                            text = stringResource(R.string.show_club_access_request_pending),
                            style = MaterialTheme.typography.bodyMedium
                        )
                    } else {
                        Button(
                            onClick = showClubViewModel::requestAccess,
                            enabled = !state.requestingAccess
                        ) {
                            if (state.requestingAccess) {
                                CircularProgressIndicator(strokeWidth = 2.dp)
                            } else {
                                Text(stringResource(R.string.show_club_request_access_button))
                            }
                        }
                    }
                }

                ShowClubStatus.Success -> {
                    val club = state.club
                    Text(
                        text = stringResource(R.string.show_club_title, club?.name.orEmpty()),
                        style = MaterialTheme.typography.headlineSmall,
                        modifier = Modifier.padding(bottom = 12.dp)
                    )
                    val members = club?.members.orEmpty().filter { it.active }
                    Text(
                        text = stringResource(R.string.show_club_members_count, members.size),
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(bottom = 10.dp)
                    )
                    Text(
                        text = stringResource(
                            R.string.show_club_open_requests_count,
                            state.openAccessRequests.size
                        ),
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(bottom = 10.dp)
                    )
                    LazyColumn(
                        modifier = Modifier.fillMaxSize()
                    ) {
                        if (state.openAccessRequests.isNotEmpty()) {
                            item(key = "open-requests-header") {
                                Text(
                                    text = stringResource(R.string.show_club_open_requests_title),
                                    style = MaterialTheme.typography.titleMedium,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 6.dp)
                                )
                            }
                            items(state.openAccessRequests, key = { "pending-${it.id}" }) { member ->
                                Text(
                                    text = member.displayName,
                                    color = MaterialTheme.colorScheme.tertiary,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 3.dp)
                                )
                            }
                            item(key = "members-header") {
                                Text(
                                    text = stringResource(R.string.show_club_members_title),
                                    style = MaterialTheme.typography.titleMedium,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 6.dp)
                                )
                            }
                        }
                        items(members, key = { it.id }) { member ->
                            Text(
                                text = member.displayName,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 4.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}
