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.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.OutlinedTextField
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.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.repository.MemberItem
import de.trainingstagebuch.app.repository.TournamentItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.viewmodel.TournamentMode
import de.trainingstagebuch.app.viewmodel.TournamentTabViewModel

@Composable
fun TournamentTabScreen(
    mode: TournamentMode,
    viewModel: TournamentTabViewModel = viewModel()
) {
    val state by viewModel.state.collectAsState()
    val context = LocalContext.current
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    LaunchedEffect(mode) {
        viewModel.setMode(mode)
    }

    Column(
        modifier = Modifier.fillMaxWidth().padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        val currentError = state.errorMessage
        if (currentError != null && currentError != dismissedError) {
            ErrorBanner(
                message = currentError.resolve(context),
                onDismiss = { dismissedError = currentError }
            )
        }

        if (state.loading) {
            CircularProgressIndicator()
        }

        TournamentSelector(
            tournaments = state.tournaments,
            selectedTournamentId = state.selectedTournamentId,
            onSelect = viewModel::selectTournament
        )

        if (state.selectedTournamentId == null) {
            if (mode == TournamentMode.Mini) {
                OutlinedTextField(
                    value = state.newMiniLocation,
                    onValueChange = viewModel::onNewMiniLocationChanged,
                    label = { Text(stringResource(R.string.tournament_location)) },
                    modifier = Modifier.fillMaxWidth()
                )
                OutlinedTextField(
                    value = state.newDate,
                    onValueChange = viewModel::onNewDateChanged,
                    label = { Text(stringResource(R.string.tournament_date)) },
                    modifier = Modifier.fillMaxWidth()
                )
                OutlinedTextField(
                    value = state.newMiniYear,
                    onValueChange = viewModel::onNewMiniYearChanged,
                    label = { Text(stringResource(R.string.tournament_year)) },
                    modifier = Modifier.fillMaxWidth()
                )
                OutlinedTextField(
                    value = state.newWinningSets,
                    onValueChange = viewModel::onNewWinningSetsChanged,
                    label = { Text(stringResource(R.string.tournament_winning_sets)) },
                    modifier = Modifier.fillMaxWidth()
                )
                Button(onClick = viewModel::createMiniTournament) {
                    Text(stringResource(R.string.tournament_create_mini))
                }
            } else {
                OutlinedTextField(
                    value = state.newTournamentName,
                    onValueChange = viewModel::onNewTournamentNameChanged,
                    label = { Text(stringResource(R.string.tournament_name)) },
                    modifier = Modifier.fillMaxWidth()
                )
                OutlinedTextField(
                    value = state.newDate,
                    onValueChange = viewModel::onNewDateChanged,
                    label = { Text(stringResource(R.string.tournament_date)) },
                    modifier = Modifier.fillMaxWidth()
                )
                OutlinedTextField(
                    value = state.newWinningSets,
                    onValueChange = viewModel::onNewWinningSetsChanged,
                    label = { Text(stringResource(R.string.tournament_winning_sets)) },
                    modifier = Modifier.fillMaxWidth()
                )
                Button(onClick = viewModel::createTournament) {
                    Text(stringResource(R.string.tournament_create))
                }
            }
        } else {
            if (state.detailLoading) {
                CircularProgressIndicator()
            }
            Text(
                text = stringResource(R.string.tournament_config_title),
                style = MaterialTheme.typography.titleMedium
            )
            OutlinedTextField(
                value = state.editName,
                onValueChange = viewModel::onEditNameChanged,
                label = { Text(stringResource(R.string.tournament_name)) },
                modifier = Modifier.fillMaxWidth()
            )
            OutlinedTextField(
                value = state.editDate,
                onValueChange = viewModel::onEditDateChanged,
                label = { Text(stringResource(R.string.tournament_date)) },
                modifier = Modifier.fillMaxWidth()
            )
            OutlinedTextField(
                value = state.editWinningSets,
                onValueChange = viewModel::onEditWinningSetsChanged,
                label = { Text(stringResource(R.string.tournament_winning_sets)) },
                modifier = Modifier.fillMaxWidth()
            )
            OutlinedTextField(
                value = state.editNumberOfTables,
                onValueChange = viewModel::onEditNumberOfTablesChanged,
                label = { Text(stringResource(R.string.tournament_tables)) },
                modifier = Modifier.fillMaxWidth()
            )
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                Button(onClick = { viewModel.onEditIsGroupChanged(true) }, enabled = !state.editIsGroupTournament) {
                    Text(stringResource(R.string.tournament_group_mode))
                }
                Button(onClick = { viewModel.onEditIsGroupChanged(false) }, enabled = state.editIsGroupTournament) {
                    Text(stringResource(R.string.tournament_knockout_mode))
                }
                Button(onClick = viewModel::saveConfig) {
                    Text(stringResource(R.string.common_save))
                }
            }

            Text(
                text = stringResource(R.string.tournament_participants_title),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(top = 8.dp)
            )
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
                MemberPicker(
                    members = state.clubMembers,
                    selectedMemberId = state.selectedMemberIdForAdd,
                    onSelect = viewModel::onSelectedMemberIdChanged,
                    modifier = Modifier.weight(1f)
                )
                Button(onClick = viewModel::addParticipant) {
                    Text(stringResource(R.string.tournament_add_participant))
                }
            }
            LazyColumn(
                modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                items(state.participants, key = { it.id }) { participant ->
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(participant.name)
                        Button(onClick = { viewModel.removeParticipant(participant.id) }) {
                            Text(stringResource(R.string.tournament_remove))
                        }
                    }
                }
            }

            Text(
                text = stringResource(R.string.tournament_matches_title),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(top = 8.dp)
            )
            LazyColumn(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                items(state.matches, key = { it.id }) { match ->
                    val draft = state.matchResultDrafts[match.id].orEmpty()
                    Column {
                        Text(stringResource(R.string.tournament_match_line, match.round, match.player1Name ?: "-", match.player2Name ?: "-"))
                        OutlinedTextField(
                            value = draft,
                            onValueChange = { viewModel.onMatchResultDraftChanged(match.id, it) },
                            label = { Text(stringResource(R.string.tournament_result_label)) },
                            modifier = Modifier.fillMaxWidth()
                        )
                        Button(onClick = { viewModel.saveMatchResult(match.id) }) {
                            Text(stringResource(R.string.tournament_save_result))
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun TournamentSelector(
    tournaments: List<TournamentItem>,
    selectedTournamentId: String?,
    onSelect: (String?) -> Unit
) {
    Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
        Button(onClick = { onSelect(null) }, enabled = selectedTournamentId != null) {
            Text(stringResource(R.string.tournament_new))
        }
        LazyColumn(modifier = Modifier.weight(1f)) {
            items(tournaments, key = { it.id }) { tournament ->
                val selected = selectedTournamentId == tournament.id
                TextButtonLike(
                    text = tournament.displayLabel(),
                    selected = selected,
                    onClick = { onSelect(tournament.id) }
                )
            }
        }
    }
}

@Composable
private fun MemberPicker(
    members: List<MemberItem>,
    selectedMemberId: String?,
    onSelect: (String?) -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(modifier = modifier) {
        items(members, key = { it.id }) { member ->
            TextButtonLike(
                text = member.displayName,
                selected = selectedMemberId == member.id,
                onClick = { onSelect(member.id) }
            )
        }
    }
}

@Composable
private fun TextButtonLike(
    text: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Button(onClick = onClick, modifier = Modifier.padding(bottom = 2.dp)) {
        Text(
            text = text,
            style = if (selected) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyMedium
        )
    }
}

private fun TournamentItem.displayLabel(): String {
    val dateText = date.orEmpty()
    return if (dateText.isBlank()) name else "$name ($dateText)"
}
