package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.clickable
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.AlertDialog
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.material3.TextButton
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.ScheduleMatchItem
import de.trainingstagebuch.app.repository.ScheduleTeamItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.utils.DateTimeUtils
import de.trainingstagebuch.app.utils.TrainingStatsMetrics
import de.trainingstagebuch.app.viewmodel.ScheduleTab
import de.trainingstagebuch.app.viewmodel.ScheduleViewModel

@Composable
fun ScheduleScreen(viewModel: ScheduleViewModel = viewModel()) {
    val state by viewModel.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.schedule_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
        ) {
            Text(
                text = stringResource(R.string.schedule_title),
                style = MaterialTheme.typography.headlineSmall
            )

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

            Row(
                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                Button(onClick = { viewModel.selectTeam(null) }) {
                    Text(stringResource(R.string.schedule_overall))
                }
                Button(onClick = viewModel::retry) {
                    Text(stringResource(R.string.common_retry))
                }
            }

            TeamSelector(
                teams = state.teams,
                selectedTeamId = state.selectedTeamId,
                onSelectTeam = viewModel::selectTeam
            )

            Row(
                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                Button(
                    onClick = { viewModel.selectTab(ScheduleTab.Schedule) },
                    enabled = state.selectedTab != ScheduleTab.Schedule
                ) {
                    Text(stringResource(R.string.schedule_tab_schedule))
                }
                Button(
                    onClick = { viewModel.selectTab(ScheduleTab.Table) },
                    enabled = state.selectedTab != ScheduleTab.Table
                ) {
                    Text(stringResource(R.string.schedule_tab_table))
                }
            }

            if (state.loading) {
                Row(
                    modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator()
                }
            }

            when (state.selectedTab) {
                ScheduleTab.Schedule -> MatchList(
                    matches = state.matches,
                    onOpenPlayers = { viewModel.openPlayerDialog(it) }
                )

                ScheduleTab.Table -> LeagueTable(rows = state.leagueTable)
            }
        }
    }

    val dialogMatch = state.matches.firstOrNull { it.id == state.playerDialogMatchId }
    if (dialogMatch != null) {
        AlertDialog(
            onDismissRequest = viewModel::closePlayerDialog,
            title = {
                Text(
                    stringResource(
                        R.string.schedule_player_dialog_title,
                        dialogMatch.homeTeamName ?: "-",
                        dialogMatch.guestTeamName ?: "-"
                    )
                )
            },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                    if (state.playerDialogLoading) {
                        CircularProgressIndicator()
                    } else if (state.playerDialogError != null) {
                        Text(
                            text = state.playerDialogError?.resolve(context).orEmpty(),
                            color = MaterialTheme.colorScheme.error
                        )
                    } else {
                        state.playerSelections.forEach { selection ->
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween
                            ) {
                                Text(selection.member.displayName, modifier = Modifier.weight(1.4f))
                                TextButton(onClick = { viewModel.toggleReady(selection.member.id) }) {
                                    Text(
                                        if (selection.isReady) {
                                            stringResource(R.string.schedule_player_ready)
                                        } else {
                                            "-"
                                        }
                                    )
                                }
                                TextButton(onClick = { viewModel.togglePlanned(selection.member.id) }) {
                                    Text(
                                        if (selection.isPlanned) {
                                            stringResource(R.string.schedule_player_planned)
                                        } else {
                                            "-"
                                        }
                                    )
                                }
                                TextButton(onClick = { viewModel.togglePlayed(selection.member.id) }) {
                                    Text(
                                        if (selection.hasPlayed) {
                                            stringResource(R.string.schedule_player_played)
                                        } else {
                                            "-"
                                        }
                                    )
                                }
                            }
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = viewModel::savePlayerSelection) {
                    Text(stringResource(R.string.common_save))
                }
            },
            dismissButton = {
                TextButton(onClick = viewModel::closePlayerDialog) {
                    Text(stringResource(R.string.predefined_cancel))
                }
            }
        )
    }
}

@Composable
private fun TeamSelector(
    teams: List<ScheduleTeamItem>,
    selectedTeamId: String?,
    onSelectTeam: (String) -> Unit
) {
    if (teams.isEmpty()) {
        Text(
            text = stringResource(R.string.schedule_no_teams),
            modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
        )
        return
    }
    LazyColumn(
        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        items(teams, key = { it.id }) { team ->
            val label = buildString {
                append(team.name)
                if (!team.leagueName.isNullOrBlank()) {
                    append(" (")
                    append(team.leagueName)
                    append(")")
                }
            }
            Text(
                text = label,
                style = if (team.id == selectedTeamId) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyMedium,
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onSelectTeam(team.id) }
                    .padding(vertical = 4.dp)
            )
        }
    }
}

@Composable
private fun MatchList(matches: List<ScheduleMatchItem>, onOpenPlayers: (String) -> Unit) {
    if (matches.isEmpty()) {
        Text(
            text = stringResource(R.string.schedule_no_games),
            modifier = Modifier.padding(top = 10.dp)
        )
        return
    }
    LazyColumn(
        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
        verticalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        items(matches, key = { it.id }) { match ->
            val date = TrainingStatsMetrics.parseDate(match.date)?.let(DateTimeUtils::formatUiDate) ?: "-"
            val result = if (match.isCompleted) {
                "${match.homeMatchPoints ?: 0}:${match.guestMatchPoints ?: 0}"
            } else {
                "-"
            }
            Column(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
                Text(stringResource(R.string.schedule_match_datetime, date, match.time.orEmpty()))
                Text(stringResource(R.string.schedule_match_pairing, match.homeTeamName ?: "-", match.guestTeamName ?: "-"))
                Text(stringResource(R.string.schedule_result_value, result))
                if (!match.locationName.isNullOrBlank()) {
                    Text(
                        "${match.locationName} ${match.locationAddress.orEmpty()} ${match.locationZip.orEmpty()} ${match.locationCity.orEmpty()}",
                        style = MaterialTheme.typography.bodySmall
                    )
                }
                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                    if (!match.code.isNullOrBlank()) {
                        OutlinedTextField(
                            value = match.code,
                            onValueChange = {},
                            readOnly = true,
                            label = { Text(stringResource(R.string.schedule_code)) },
                            modifier = Modifier.weight(1f)
                        )
                    }
                    Button(onClick = { onOpenPlayers(match.id) }) {
                        Text(stringResource(R.string.schedule_players_button))
                    }
                }
            }
        }
    }
}

@Composable
private fun LeagueTable(rows: List<de.trainingstagebuch.app.repository.ScheduleLeagueTableRow>) {
    if (rows.isEmpty()) {
        Text(
            text = stringResource(R.string.schedule_no_table_data),
            modifier = Modifier.padding(top = 10.dp)
        )
        return
    }
    LazyColumn(
        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        items(rows, key = { it.teamId }) { row ->
            Text(
                stringResource(
                    R.string.schedule_table_row_line,
                    row.teamName,
                    row.matchPoints,
                    row.setsWon,
                    row.setsLost,
                    row.tablePoints
                )
            )
        }
    }
}
