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.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
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.HomeStatus
import de.trainingstagebuch.app.viewmodel.HomeViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    currentClubId: String?,
    onSelectClubAndOpenStats: (String) -> Unit,
    onNavigateToCreateClub: () -> Unit,
    onNavigateToShowClub: (String) -> Unit,
    onNavigateToMembers: () -> Unit,
    onNavigateToDiary: () -> Unit,
    onNavigateToSchedule: () -> Unit,
    onNavigateToTournaments: () -> Unit,
    onNavigateToTrainingStats: () -> Unit,
    onNavigateToPredefinedActivities: () -> Unit,
    onNavigateToClubSettings: () -> Unit,
    onNavigateToPendingApprovals: () -> Unit,
    onNavigateToPermissions: () -> Unit,
    onNavigateToTeamManagement: () -> Unit,
    onNavigateToMemberTransferSettings: () -> Unit,
    onNavigateToMyTischtennisAccount: () -> Unit,
    onNavigateToLogs: () -> Unit,
    onNavigateToPersonalSettings: () -> Unit,
    onNavigateToImpressum: () -> Unit,
    onNavigateToDatenschutz: () -> Unit,
    onLogout: () -> Unit,
    homeViewModel: HomeViewModel = viewModel()
) {
    val state by homeViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }
    var clubsExpanded by remember { mutableStateOf(false) }

    val clubs = state.data?.clubs.orEmpty()
    var selectedClubId by remember(currentClubId, clubs) {
        val preselected = currentClubId?.trim().orEmpty().takeIf { id -> clubs.any { it.id == id } }
        mutableStateOf(preselected ?: clubs.firstOrNull()?.id.orEmpty())
    }

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

    Scaffold(
        topBar = {
            TrainingstagebuchTopBar(title = stringResource(R.string.home_title))
        },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(24.dp),
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            when (state.status) {
                HomeStatus.Idle, HomeStatus.Loading -> {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 40.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator()
                        Text(
                            text = stringResource(R.string.home_loading),
                            modifier = Modifier.padding(top = 12.dp)
                        )
                    }
                }

                HomeStatus.Error -> {
                    val currentError = state.errorMessage
                    if (currentError != null && currentError != dismissedError) {
                        ErrorBanner(
                            message = currentError.resolve(context),
                            onDismiss = { dismissedError = currentError },
                            modifier = Modifier.fillMaxWidth()
                        )
                    } else {
                        Text(
                            text = stringResource(R.string.error_unknown),
                            color = MaterialTheme.colorScheme.error,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                    Button(
                        onClick = homeViewModel::load,
                        modifier = Modifier.padding(top = 12.dp)
                    ) {
                        Text(stringResource(R.string.home_retry))
                    }
                }

                HomeStatus.Success -> {
                    Text(
                        text = stringResource(R.string.home_select_club_hint),
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 8.dp, bottom = 8.dp)
                    )

                    ExposedDropdownMenuBox(
                        expanded = clubsExpanded,
                        onExpandedChange = {
                            if (clubs.isNotEmpty()) {
                                clubsExpanded = !clubsExpanded
                            }
                        }
                    ) {
                        TextField(
                            value = clubs.firstOrNull { it.id == selectedClubId }?.name.orEmpty(),
                            onValueChange = {},
                            readOnly = true,
                            label = { Text(stringResource(R.string.home_select_club_label)) },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = clubsExpanded) },
                            modifier = Modifier
                                .menuAnchor(
                                    type = MenuAnchorType.PrimaryNotEditable,
                                    enabled = clubs.isNotEmpty()
                                )
                                .fillMaxWidth()
                        )

                        ExposedDropdownMenu(
                            expanded = clubsExpanded,
                            onDismissRequest = { clubsExpanded = false }
                        ) {
                            clubs.forEach { club ->
                                DropdownMenuItem(
                                    text = { Text(club.name) },
                                    onClick = {
                                        selectedClubId = club.id
                                        clubsExpanded = false
                                        onSelectClubAndOpenStats(club.id)
                                    }
                                )
                            }
                        }
                    }

                    if (clubs.isEmpty()) {
                        Text(
                            text = stringResource(R.string.home_no_clubs_hint),
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 8.dp)
                        )
                    }

                    Button(
                        onClick = onNavigateToCreateClub,
                        modifier = Modifier.padding(top = 16.dp)
                    ) {
                        Text(stringResource(R.string.create_club_create_button))
                    }
                }
            }
        }
    }
}
