package de.tsschulz.tt_tagebuch.app.ui

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import de.tsschulz.tt_tagebuch.app.AppDependencies
import de.tsschulz.tt_tagebuch.shared.api.models.Club
import de.tsschulz.tt_tagebuch.shared.api.models.CreateTrainingTimeBody
import de.tsschulz.tt_tagebuch.shared.api.models.Member
import de.tsschulz.tt_tagebuch.shared.api.models.MemberDataQualityRequirements
import de.tsschulz.tt_tagebuch.shared.api.models.TrainingGroupDto
import de.tsschulz.tt_tagebuch.shared.api.models.TrainingGroupMemberBrief
import de.tsschulz.tt_tagebuch.shared.api.models.TrainingTimeDto
import de.tsschulz.tt_tagebuch.shared.api.models.UpdateClubSettingsBody
import de.tsschulz.tt_tagebuch.shared.api.models.UpdateTrainingTimeBody
import de.tsschulz.tt_tagebuch.shared.api.models.canReadClubSettings
import de.tsschulz.tt_tagebuch.shared.api.models.canReadMembers
import de.tsschulz.tt_tagebuch.shared.api.models.canWriteClubSettings
import de.tsschulz.tt_tagebuch.shared.i18n.MobileStrings
import kotlinx.coroutines.launch

private val ClubSettingsPad = 20.dp
private val ClubSettingsTouchMin = 48.dp
private val ClubSettingsCardElev = 1.dp

private enum class ClubSettingsWebTab {
    Settings,
    TrainingGroups,
    TrainingTimes,
}

private data class GermanStateOption(val code: String, val name: String)

private val germanStatesClubSettings: List<GermanStateOption> = listOf(
    GermanStateOption("DE-BW", "Baden-Württemberg"),
    GermanStateOption("DE-BY", "Bayern"),
    GermanStateOption("DE-BE", "Berlin"),
    GermanStateOption("DE-BB", "Brandenburg"),
    GermanStateOption("DE-HB", "Bremen"),
    GermanStateOption("DE-HH", "Hamburg"),
    GermanStateOption("DE-HE", "Hessen"),
    GermanStateOption("DE-MV", "Mecklenburg-Vorpommern"),
    GermanStateOption("DE-NI", "Niedersachsen"),
    GermanStateOption("DE-NW", "Nordrhein-Westfalen"),
    GermanStateOption("DE-RP", "Rheinland-Pfalz"),
    GermanStateOption("DE-SL", "Saarland"),
    GermanStateOption("DE-SN", "Sachsen"),
    GermanStateOption("DE-ST", "Sachsen-Anhalt"),
    GermanStateOption("DE-SH", "Schleswig-Holstein"),
    GermanStateOption("DE-TH", "Thüringen"),
)

private fun defaultQuality(): MemberDataQualityRequirements = MemberDataQualityRequirements()

private fun normalizeQuality(m: MemberDataQualityRequirements?): MemberDataQualityRequirements {
    val d = defaultQuality()
    if (m == null) return d
    return MemberDataQualityRequirements(
        requireStreet = m.requireStreet,
        requirePostalCode = m.requirePostalCode,
        requireCity = m.requireCity,
        requirePhone = m.requirePhone,
        requireEmail = m.requireEmail,
    )
}

private fun sortedTrainingGroupsForClubSettings(groups: List<TrainingGroupDto>): List<TrainingGroupDto> =
    groups.sortedWith(
        compareBy<TrainingGroupDto> { if (it.isPreset) 0 else 1 }
            .thenBy { it.sortOrder }
            .thenBy { it.name.lowercase() },
    )

private fun parseClockToApi(raw: String): String? {
    val parts = raw.trim().split(':')
    if (parts.size != 2) return null
    val h = parts[0].trim().toIntOrNull() ?: return null
    val m = parts[1].trim().take(2).padEnd(2, '0').toIntOrNull() ?: return null
    if (h !in 0..23 || m !in 0..59) return null
    return h.toString().padStart(2, '0') + ":" + m.toString().padStart(2, '0')
}

private fun trainingWeekdayLabel(languageCode: String, weekday: Int): String {
    fun g(key: String, fb: String) = MobileStrings.get(languageCode, key, fb)
    return when (weekday) {
        0 -> g("trainingTimesTab.sunday", "Sonntag")
        1 -> g("trainingTimesTab.monday", "Montag")
        2 -> g("trainingTimesTab.tuesday", "Dienstag")
        3 -> g("trainingTimesTab.wednesday", "Mittwoch")
        4 -> g("trainingTimesTab.thursday", "Donnerstag")
        5 -> g("trainingTimesTab.friday", "Freitag")
        6 -> g("trainingTimesTab.saturday", "Samstag")
        else -> ""
    }
}

private fun trainingGroupMemberLabel(m: TrainingGroupMemberBrief): String {
    val fn = m.firstName.orEmpty().trim()
    val ln = m.lastName.orEmpty().trim()
    return "$fn $ln".trim().ifBlank { "#${m.id}" }
}

private fun formatTimeDisplay(t: String): String = t.trim().take(5)

@Composable
private fun ClubSettingsTopBar(title: String, onBack: () -> Unit) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        IconButton(onClick = onBack) {
            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null)
        }
        Text(title, style = MaterialTheme.typography.h6, fontWeight = FontWeight.SemiBold)
    }
    Spacer(modifier = Modifier.height(8.dp))
}

@Composable
private fun RowSwitchClubSettings(label: String, checked: Boolean, onChecked: (Boolean) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Text(label, modifier = Modifier.weight(1f))
        androidx.compose.material.Switch(checked = checked, onCheckedChange = onChecked)
    }
}

@Composable
internal fun MobileClubSettingsScreen(dependencies: AppDependencies, onBack: () -> Unit) {
    val languageCode = LocalLanguageCode.current
    fun tr(key: String, fb: String) = MobileStrings.get(languageCode, key, fb)
    val clubState by dependencies.clubManager.state.collectAsState()
    val clubId = clubState.currentClubId ?: return
    val perms = clubState.currentPermissions
    val scope = rememberCoroutineScope()
    var mainTab by remember { mutableStateOf(ClubSettingsWebTab.Settings) }

    var club by remember { mutableStateOf<Club?>(null) }
    var loadError by remember { mutableStateOf<String?>(null) }
    var loading by remember { mutableStateOf(true) }
    var saving by remember { mutableStateOf(false) }
    var savedHint by remember { mutableStateOf(false) }

    var greeting by remember { mutableStateOf("") }
    var associationNumber by remember { mutableStateOf("") }
    var countryCode by remember { mutableStateOf("DE") }
    var stateCode by remember { mutableStateOf("") }
    var stateMenu by remember { mutableStateOf(false) }
    var myTtNickname by remember { mutableStateOf("") }
    var autoFetch by remember { mutableStateOf(false) }
    var quality by remember { mutableStateOf(defaultQuality()) }

    LaunchedEffect(clubId, mainTab) {
        if (mainTab != ClubSettingsWebTab.Settings) return@LaunchedEffect
        loading = true
        loadError = null
        club = runCatching { dependencies.clubManager.fetchClubDetail(clubId) }
            .onFailure { loadError = it.message }
            .getOrNull()
        val c = club
        if (c != null) {
            greeting = c.greetingText.orEmpty()
            associationNumber = c.associationMemberNumber.orEmpty()
            countryCode = c.countryCode?.ifBlank { "DE" } ?: "DE"
            stateCode = c.stateCode.orEmpty()
            myTtNickname = c.myTischtennisFedNickname.orEmpty()
            autoFetch = c.autoFetchRankings == true
            quality = normalizeQuality(c.memberDataQualityRequirements)
        }
        loading = false
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(ClubSettingsPad),
    ) {
        ClubSettingsTopBar(tr("clubSettings.title", "Vereins-Einstellungen"), onBack)
        if (perms?.canReadClubSettings() != true) {
            Text(tr("mobile.noAccess", "Keine Berechtigung."))
            return@Column
        }
        TabRow(
            selectedTabIndex = mainTab.ordinal,
            backgroundColor = MaterialTheme.colors.surface,
            contentColor = MaterialTheme.colors.onSurface,
        ) {
            ClubSettingsWebTab.values().forEach { tab ->
                Tab(
                    selected = mainTab == tab,
                    onClick = { mainTab = tab },
                    text = {
                        Text(
                            when (tab) {
                                ClubSettingsWebTab.Settings -> tr("clubSettings.settings", "Einstellungen")
                                ClubSettingsWebTab.TrainingGroups -> tr("clubSettings.trainingGroups", "Trainingsgruppen")
                                ClubSettingsWebTab.TrainingTimes -> tr("clubSettings.trainingTimes", "Trainingszeiten")
                            },
                            style = MaterialTheme.typography.body2,
                            maxLines = 2,
                        )
                    },
                )
            }
        }
        Spacer(modifier = Modifier.height(8.dp))

        when (mainTab) {
            ClubSettingsWebTab.Settings -> {
                when {
                    loading -> CircularProgressIndicator(modifier = Modifier.padding(top = 24.dp))
                    loadError != null -> Text(loadError!!, color = MaterialTheme.colors.error)
                    club == null -> Text(tr("clubSettings.loadFailed", "Einstellungen konnten nicht geladen werden"))
                    else -> Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState()),
                    ) {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            elevation = ClubSettingsCardElev,
                        ) {
                            Column(Modifier.padding(16.dp)) {
                                Text(tr("clubSettings.greetingText", "Begrüßungstext"), fontWeight = FontWeight.SemiBold)
                                OutlinedTextField(
                                    value = greeting,
                                    onValueChange = { greeting = it },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(top = 8.dp),
                                    minLines = 6,
                                    label = { Text(tr("clubSettings.greetingPlaceholder", "Begrüßungstext für Heimspiele...")) },
                                )
                                Card(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(top = 10.dp),
                                    elevation = 0.dp,
                                    backgroundColor = MaterialTheme.colors.background,
                                ) {
                                    Column(Modifier.padding(10.dp)) {
                                        Text(
                                            tr("clubSettings.placeholders", "Platzhalter"),
                                            fontWeight = FontWeight.SemiBold,
                                            style = MaterialTheme.typography.subtitle2,
                                        )
                                        Spacer(Modifier.height(6.dp))
                                        Text(
                                            "{home} — ${tr("clubSettings.homeTeam", "Name Heimmannschaft")}",
                                            style = MaterialTheme.typography.caption,
                                            fontFamily = FontFamily.Monospace,
                                        )
                                        Text(
                                            "{guest} — ${tr("clubSettings.guestTeam", "Name Gastmannschaft")}",
                                            style = MaterialTheme.typography.caption,
                                            fontFamily = FontFamily.Monospace,
                                        )
                                        Text(
                                            "{homeplayers} — ${tr("clubSettings.homePlayers", "Spieler und Doppel Heimmannschaft")}",
                                            style = MaterialTheme.typography.caption,
                                            fontFamily = FontFamily.Monospace,
                                        )
                                        Text(
                                            "{guestplayers} — ${tr("clubSettings.guestPlayers", "Spieler und Doppel Gastmannschaft")}",
                                            style = MaterialTheme.typography.caption,
                                            fontFamily = FontFamily.Monospace,
                                        )
                                    }
                                }
                                Text(
                                    tr("clubSettings.greetingHint", "Dieser Text erscheint im Reiter \"Begrüßung\" des Spielberichtsbogens."),
                                    style = MaterialTheme.typography.caption,
                                    modifier = Modifier.padding(top = 8.dp),
                                )
                            }
                        }

                        Spacer(Modifier.height(12.dp))
                        Card(modifier = Modifier.fillMaxWidth(), elevation = ClubSettingsCardElev) {
                            Column(Modifier.padding(16.dp)) {
                                Text(tr("clubSettings.associationMemberNumber", "Verbands-Mitgliedsnummer"), fontWeight = FontWeight.SemiBold)
                                OutlinedTextField(
                                    value = associationNumber,
                                    onValueChange = { associationNumber = it },
                                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                                    singleLine = true,
                                    placeholder = { Text(tr("clubSettings.associationMemberNumberPlaceholder", "z. B. 12-3456")) },
                                )
                            }
                        }

                        Spacer(Modifier.height(12.dp))
                        Card(modifier = Modifier.fillMaxWidth(), elevation = ClubSettingsCardElev) {
                            Column(Modifier.padding(16.dp)) {
                                Text(
                                    tr("clubSettings.calendarRegion", "Kalenderregion"),
                                    fontWeight = FontWeight.SemiBold,
                                )
                                Text(
                                    tr(
                                        "clubSettings.calendarRegionHint",
                                        "Die Region wird für Schulferien und gesetzliche Feiertage im Kalender genutzt.",
                                    ),
                                    style = MaterialTheme.typography.caption,
                                    modifier = Modifier.padding(top = 4.dp),
                                )
                                Text(
                                    tr("clubSettings.country", "Land"),
                                    style = MaterialTheme.typography.caption,
                                    modifier = Modifier.padding(top = 8.dp),
                                )
                                Box {
                                    TextButton(onClick = { /* nur DE wie Web */ }, enabled = false, modifier = Modifier.fillMaxWidth()) {
                                        Text(tr("clubSettings.countryGermany", "Deutschland"))
                                    }
                                }
                                Text(
                                    tr("clubSettings.state", "Bundesland"),
                                    style = MaterialTheme.typography.caption,
                                    modifier = Modifier.padding(top = 8.dp),
                                )
                                Box {
                                    TextButton(onClick = { stateMenu = true }, modifier = Modifier.fillMaxWidth()) {
                                        Text(
                                            germanStatesClubSettings.find { it.code == stateCode }?.name
                                                ?: tr("mobile.stateNotSet", "Nicht gesetzt"),
                                        )
                                    }
                                    DropdownMenu(expanded = stateMenu, onDismissRequest = { stateMenu = false }) {
                                        DropdownMenuItem(
                                            onClick = {
                                                stateCode = ""
                                                stateMenu = false
                                            },
                                        ) { Text(tr("mobile.stateNotSet", "Nicht gesetzt")) }
                                        germanStatesClubSettings.forEach { s ->
                                            DropdownMenuItem(
                                                onClick = {
                                                    stateCode = s.code
                                                    stateMenu = false
                                                },
                                            ) { Text(s.name) }
                                        }
                                    }
                                }
                            }
                        }

                        Spacer(Modifier.height(12.dp))
                        Card(modifier = Modifier.fillMaxWidth(), elevation = ClubSettingsCardElev) {
                            Column(Modifier.padding(16.dp)) {
                                Text(tr("clubSettings.myTischtennisRankings", "myTischtennis TTR/QTTR-Ranglisten"), fontWeight = FontWeight.SemiBold)
                                Text(
                                    tr(
                                        "clubSettings.myTischtennisRankingsHint",
                                        "Automatischer Abruf der Vereins-Rangliste für TTR- und QTTR-Updates der Mitglieder.",
                                    ),
                                    style = MaterialTheme.typography.caption,
                                    modifier = Modifier.padding(top = 4.dp),
                                )
                                RowSwitchClubSettings(tr("clubSettings.autoFetchRankings", "Ranglisten automatisch abrufen"), autoFetch) {
                                    autoFetch = it
                                }
                                if (autoFetch) {
                                    OutlinedTextField(
                                        value = myTtNickname,
                                        onValueChange = { myTtNickname = it },
                                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                                        label = { Text(tr("clubSettings.myTischtennisFedNickname", "Verbandskürzel")) },
                                        placeholder = { Text(tr("clubSettings.myTischtennisFedNicknamePlaceholder", "z. B. HeTTV")) },
                                        singleLine = true,
                                    )
                                    Text(
                                        tr(
                                            "clubSettings.rankingsUsesAssociationNumber",
                                            "Die Vereinsnummer für den Ranglisten-Abruf entspricht der Verbands-Mitgliedsnummer oben.",
                                        ),
                                        style = MaterialTheme.typography.caption,
                                        modifier = Modifier.padding(top = 8.dp),
                                    )
                                }
                            }
                        }

                        Spacer(Modifier.height(12.dp))
                        Card(modifier = Modifier.fillMaxWidth(), elevation = ClubSettingsCardElev) {
                            Column(Modifier.padding(16.dp)) {
                                Text(tr("clubSettings.memberDataQuality", "Datenqualität Mitglieder"), fontWeight = FontWeight.SemiBold)
                                Text(
                                    tr(
                                        "clubSettings.memberDataQualityHint",
                                        "Diese Felder zählen auf der Mitgliederseite als nötig. Alle Felder bleiben weiterhin eingebbar.",
                                    ),
                                    style = MaterialTheme.typography.caption,
                                    modifier = Modifier.padding(top = 4.dp, bottom = 8.dp),
                                )
                                RowSwitchClubSettings(tr("clubSettings.requireStreet", "Straße nötig"), quality.requireStreet) {
                                    quality = quality.copy(requireStreet = it)
                                }
                                RowSwitchClubSettings(tr("clubSettings.requirePostalCode", "PLZ nötig"), quality.requirePostalCode) {
                                    quality = quality.copy(requirePostalCode = it)
                                }
                                RowSwitchClubSettings(tr("clubSettings.requireCity", "Ort nötig"), quality.requireCity) {
                                    quality = quality.copy(requireCity = it)
                                }
                                RowSwitchClubSettings(tr("clubSettings.requirePhone", "Telefonnummer nötig"), quality.requirePhone) {
                                    quality = quality.copy(requirePhone = it)
                                }
                                RowSwitchClubSettings(tr("clubSettings.requireEmail", "E-Mail-Adresse nötig"), quality.requireEmail) {
                                    quality = quality.copy(requireEmail = it)
                                }
                            }
                        }

                        Spacer(Modifier.height(12.dp))
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp),
                        ) {
                            Button(
                                onClick = {
                                    if (perms.canWriteClubSettings()) {
                                        scope.launch {
                                            saving = true
                                            savedHint = false
                                            runCatching {
                                                dependencies.clubManager.updateClubSettings(
                                                    clubId,
                                                    UpdateClubSettingsBody(
                                                        greetingText = greeting,
                                                        associationMemberNumber = associationNumber,
                                                        countryCode = countryCode,
                                                        stateCode = stateCode.ifBlank { null },
                                                        myTischtennisFedNickname = myTtNickname.ifBlank { null },
                                                        autoFetchRankings = autoFetch,
                                                        memberDataQualityRequirements = normalizeQuality(quality),
                                                    ),
                                                )
                                                club = dependencies.clubManager.fetchClubDetail(clubId)
                                                savedHint = true
                                            }.onFailure { loadError = it.message }
                                            saving = false
                                        }
                                    }
                                },
                                enabled = !saving && perms.canWriteClubSettings(),
                                modifier = Modifier.heightIn(min = ClubSettingsTouchMin),
                            ) {
                                Text(tr("clubSettings.save", "Speichern"))
                            }
                            if (savedHint) {
                                Text(
                                    tr("clubSettings.saved", "Gespeichert"),
                                    color = MaterialTheme.colors.primary,
                                    fontWeight = FontWeight.SemiBold,
                                )
                            }
                        }
                    }
                }
            }
            ClubSettingsWebTab.TrainingGroups -> ClubTrainingGroupsTabContent(
                dependencies = dependencies,
                clubId = clubId,
                canWrite = perms.canWriteClubSettings(),
                canReadMembers = perms.canReadMembers(),
            )
            ClubSettingsWebTab.TrainingTimes -> ClubTrainingTimesTabContent(
                dependencies = dependencies,
                clubId = clubId,
                canWrite = perms.canWriteClubSettings(),
            )
        }
    }
}

@Composable
private fun ClubTrainingGroupsTabContent(
    dependencies: AppDependencies,
    clubId: Int,
    canWrite: Boolean,
    canReadMembers: Boolean,
) {
    val languageCode = LocalLanguageCode.current
    fun tr(key: String, fb: String) = MobileStrings.get(languageCode, key, fb)
    val scope = rememberCoroutineScope()
    var groups by remember { mutableStateOf<List<TrainingGroupDto>>(emptyList()) }
    var members by remember { mutableStateOf<List<Member>>(emptyList()) }
    var loading by remember { mutableStateOf(true) }
    var error by remember { mutableStateOf<String?>(null) }
    var refresh by remember { mutableIntStateOf(0) }
    var showAdd by remember { mutableStateOf(false) }
    var newName by remember { mutableStateOf("") }
    var editing by remember { mutableStateOf<TrainingGroupDto?>(null) }
    var editName by remember { mutableStateOf("") }
    var deleteTarget by remember { mutableStateOf<TrainingGroupDto?>(null) }
    var memberPickGroupId by remember { mutableStateOf<Int?>(null) }
    var memberMenu by remember { mutableStateOf(false) }

    LaunchedEffect(clubId, refresh) {
        loading = true
        error = null
        runCatching {
            groups = sortedTrainingGroupsForClubSettings(dependencies.membersManager.listTrainingGroups(clubId))
            members = if (canReadMembers) {
                dependencies.membersManager.listMembersForClub(clubId, activeOnly = true)
            } else {
                emptyList()
            }
        }.onFailure { error = it.message }
        loading = false
    }

    fun availableForGroup(gid: Int): List<Member> {
        val g = groups.find { it.id == gid } ?: return members
        val inGroup = g.members.map { it.id }.toSet()
        return members.filter { it.id !in inGroup }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(tr("trainingGroupsTab.groups", "Gruppen"), style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.SemiBold)
            if (canWrite) {
                TextButton(onClick = { showAdd = !showAdd }) {
                    Text(tr("trainingGroupsTab.newGroup", "+ Neue Gruppe"))
                }
            }
        }
        if (showAdd && canWrite) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                OutlinedTextField(
                    value = newName,
                    onValueChange = { newName = it },
                    modifier = Modifier.weight(1f),
                    singleLine = true,
                    placeholder = { Text(tr("trainingGroupsTab.groupName", "Gruppenname")) },
                )
                Button(
                    onClick = {
                        scope.launch {
                            runCatching {
                                dependencies.membersManager.createClubTrainingGroup(clubId, newName)
                                newName = ""
                                showAdd = false
                                refresh++
                            }.onFailure { error = it.message }
                        }
                    },
                    enabled = newName.isNotBlank(),
                ) { Text(tr("trainingGroupsTab.create", "Erstellen")) }
                OutlinedButton(onClick = { showAdd = false; newName = "" }) {
                    Text(tr("trainingGroupsTab.cancel", "Abbrechen"))
                }
            }
        }
        when {
            loading -> CircularProgressIndicator(modifier = Modifier.padding(top = 24.dp))
            error != null -> Text(error!!, color = MaterialTheme.colors.error)
            else -> LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                items(groups, key = { it.id }) { g ->
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        elevation = ClubSettingsCardElev,
                        backgroundColor = if (g.isPreset) {
                            MaterialTheme.colors.primary.copy(alpha = 0.06f)
                        } else {
                            MaterialTheme.colors.surface
                        },
                    ) {
                        Column(Modifier.padding(12.dp)) {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically,
                            ) {
                                Text(g.name, fontWeight = FontWeight.SemiBold)
                                if (canWrite && !g.isPreset) {
                                    Row {
                                        TextButton(onClick = { editing = g; editName = g.name }) {
                                            Text(tr("trainingGroupsTab.edit", "Bearbeiten"))
                                        }
                                        TextButton(onClick = { deleteTarget = g }) {
                                            Text(tr("trainingGroupsTab.delete", "Löschen"))
                                        }
                                    }
                                }
                            }
                            Text(
                                "${g.members.size} ${tr("trainingGroupsTab.members", "Mitglieder")}",
                                style = MaterialTheme.typography.caption,
                                modifier = Modifier.padding(top = 4.dp),
                            )
                            if (g.members.isNotEmpty()) {
                                Column(Modifier.padding(top = 6.dp)) {
                                    g.members.forEach { m ->
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            modifier = Modifier.fillMaxWidth(),
                                        ) {
                                            Text(trainingGroupMemberLabel(m), modifier = Modifier.weight(1f))
                                            if (canWrite) {
                                                TextButton(
                                                    onClick = {
                                                        scope.launch {
                                                            runCatching {
                                                                dependencies.membersManager.removeMemberFromTrainingGroup(clubId, g.id, m.id)
                                                                refresh++
                                                            }.onFailure { error = it.message }
                                                        }
                                                    },
                                                ) {
                                                    Text("× ${tr("trainingGroupsTab.remove", "Entfernen")}")
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (canWrite && canReadMembers) {
                                Box(modifier = Modifier.padding(top = 8.dp)) {
                                    TextButton(
                                        onClick = {
                                            memberPickGroupId = g.id
                                            memberMenu = true
                                        },
                                        enabled = availableForGroup(g.id).isNotEmpty(),
                                        modifier = Modifier.fillMaxWidth(),
                                    ) {
                                        Text(
                                            if (availableForGroup(g.id).isEmpty()) {
                                                tr("trainingGroupsTab.noMembersAvailable", "Keine Mitglieder verfügbar")
                                            } else {
                                                tr("trainingGroupsTab.addMember", "Mitglied hinzufügen...")
                                            },
                                        )
                                    }
                                    DropdownMenu(
                                        expanded = memberMenu && memberPickGroupId == g.id,
                                        onDismissRequest = { memberMenu = false; memberPickGroupId = null },
                                    ) {
                                        availableForGroup(g.id).forEach { mem ->
                                            DropdownMenuItem(
                                                onClick = {
                                                    scope.launch {
                                                        runCatching {
                                                            dependencies.membersManager.addMemberToTrainingGroup(clubId, g.id, mem.id)
                                                            memberMenu = false
                                                            memberPickGroupId = null
                                                            refresh++
                                                        }.onFailure { error = it.message }
                                                    }
                                                },
                                            ) {
                                                Text("${mem.firstName} ${mem.lastName}".trim())
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (editing != null) {
        StableAlertDialog(
            onDismissRequest = { editing = null },
            title = { Text(tr("trainingGroupsTab.editGroup", "Gruppe bearbeiten")) },
            text = {
                OutlinedTextField(
                    value = editName,
                    onValueChange = { editName = it },
                    singleLine = true,
                    placeholder = { Text(tr("trainingGroupsTab.groupName", "Gruppenname")) },
                    modifier = Modifier.fillMaxWidth(),
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        val eg = editing ?: return@TextButton
                        scope.launch {
                            runCatching {
                                dependencies.membersManager.updateClubTrainingGroup(clubId, eg.id, editName, eg.sortOrder)
                                editing = null
                                refresh++
                            }.onFailure { error = it.message }
                        }
                    },
                    enabled = editName.isNotBlank(),
                ) { Text(tr("common.save", "Speichern")) }
            },
            dismissButton = {
                TextButton(onClick = { editing = null }) { Text(tr("trainingGroupsTab.cancel", "Abbrechen")) }
            },
        )
    }

    if (deleteTarget != null) {
        val dg = deleteTarget!!
        StableAlertDialog(
            onDismissRequest = { deleteTarget = null },
            title = { Text(tr("trainingGroupsTab.delete", "Löschen")) },
            text = {
                Text(
                    "„${dg.name}“ löschen? Zuordnungen werden entfernt.",
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        scope.launch {
                            runCatching {
                                dependencies.membersManager.deleteClubTrainingGroup(clubId, dg.id)
                                deleteTarget = null
                                refresh++
                            }.onFailure { error = it.message }
                        }
                    },
                ) { Text(tr("trainingGroupsTab.delete", "Löschen")) }
            },
            dismissButton = {
                TextButton(onClick = { deleteTarget = null }) { Text(tr("trainingGroupsTab.cancel", "Abbrechen")) }
            },
        )
    }
}

@Composable
private fun ClubTrainingTimesTabContent(
    dependencies: AppDependencies,
    clubId: Int,
    canWrite: Boolean,
) {
    val languageCode = LocalLanguageCode.current
    fun tr(key: String, fb: String) = MobileStrings.get(languageCode, key, fb)
    val scope = rememberCoroutineScope()
    var groups by remember { mutableStateOf<List<TrainingGroupDto>>(emptyList()) }
    var loading by remember { mutableStateOf(true) }
    var error by remember { mutableStateOf<String?>(null) }
    var refresh by remember { mutableIntStateOf(0) }
    var addForGroupId by remember { mutableStateOf<Int?>(null) }
    var newWeekday by remember { mutableIntStateOf(1) }
    var newStart by remember { mutableStateOf("") }
    var newEnd by remember { mutableStateOf("") }
    var weekdayMenuNew by remember { mutableStateOf(false) }
    var editing by remember { mutableStateOf<TrainingTimeDto?>(null) }
    var editWeekday by remember { mutableIntStateOf(1) }
    var editStart by remember { mutableStateOf("") }
    var editEnd by remember { mutableStateOf("") }
    var weekdayMenuEdit by remember { mutableStateOf(false) }
    var deleteTimeId by remember { mutableStateOf<Int?>(null) }

    LaunchedEffect(clubId, refresh) {
        loading = true
        error = null
        runCatching {
            groups = dependencies.membersManager.trainingScheduleGroups(clubId)
        }.onFailure { error = it.message }
        loading = false
    }

    Column(modifier = Modifier.fillMaxSize()) {
        error?.let {
            Text(it, color = MaterialTheme.colors.error, modifier = Modifier.padding(bottom = 8.dp))
        }
        when {
            loading -> CircularProgressIndicator(modifier = Modifier.padding(top = 24.dp))
            else -> LazyColumn(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(16.dp),
            ) {
        items(groups, key = { it.id }) { g ->
            Card(modifier = Modifier.fillMaxWidth(), elevation = ClubSettingsCardElev) {
                Column(Modifier.padding(12.dp)) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Text(g.name, style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.SemiBold)
                        if (canWrite) {
                            TextButton(onClick = { addForGroupId = g.id; newWeekday = 1; newStart = ""; newEnd = "" }) {
                                Text(tr("trainingTimesTab.addTime", "+ Zeit hinzufügen"))
                            }
                        }
                    }
                    if (addForGroupId == g.id && canWrite) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp),
                        ) {
                            Text(tr("trainingTimesTab.weekday", "Wochentag:"), style = MaterialTheme.typography.caption)
                            Box {
                                TextButton(onClick = { weekdayMenuNew = true }) {
                                    Text(trainingWeekdayLabel(languageCode, newWeekday))
                                }
                                DropdownMenu(expanded = weekdayMenuNew, onDismissRequest = { weekdayMenuNew = false }) {
                                    (0..6).forEach { d ->
                                        DropdownMenuItem(
                                            onClick = {
                                                newWeekday = d
                                                weekdayMenuNew = false
                                            },
                                        ) { Text(trainingWeekdayLabel(languageCode, d)) }
                                    }
                                }
                            }
                            OutlinedTextField(
                                value = newStart,
                                onValueChange = { newStart = it },
                                label = { Text(tr("trainingTimesTab.from", "Von:")) },
                                placeholder = { Text("08:00") },
                                singleLine = true,
                                modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
                            )
                            OutlinedTextField(
                                value = newEnd,
                                onValueChange = { newEnd = it },
                                label = { Text(tr("trainingTimesTab.to", "Bis:")) },
                                placeholder = { Text("10:00") },
                                singleLine = true,
                                modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
                            )
                            Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 8.dp)) {
                                Button(
                                    onClick = {
                                        val s = parseClockToApi(newStart) ?: return@Button
                                        val e = parseClockToApi(newEnd) ?: return@Button
                                        if (s >= e) {
                                            error = tr("trainingTimesTab.saveError", "Ungültige Zeitspanne")
                                            return@Button
                                        }
                                        scope.launch {
                                            runCatching {
                                                dependencies.membersManager.createClubTrainingTime(
                                                    clubId,
                                                    CreateTrainingTimeBody(
                                                        trainingGroupId = g.id,
                                                        weekday = newWeekday,
                                                        startTime = s,
                                                        endTime = e,
                                                    ),
                                                )
                                                addForGroupId = null
                                                refresh++
                                                error = null
                                            }.onFailure { error = it.message }
                                        }
                                    },
                                ) { Text(tr("trainingTimesTab.create", "Erstellen")) }
                                OutlinedButton(onClick = { addForGroupId = null }) {
                                    Text(tr("trainingTimesTab.cancel", "Abbrechen"))
                                }
                            }
                        }
                    }
                    val times = g.trainingTimes.sortedWith(compareBy({ it.weekday }, { it.startTime }))
                    if (times.isEmpty()) {
                        Text(tr("trainingTimesTab.noTimes", "Keine Trainingszeiten definiert"), modifier = Modifier.padding(top = 8.dp))
                    } else {
                        Column(Modifier.padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
                            times.forEach { t ->
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text(trainingWeekdayLabel(languageCode, t.weekday), fontWeight = FontWeight.Medium)
                                        Text("${formatTimeDisplay(t.startTime)} – ${formatTimeDisplay(t.endTime)}")
                                    }
                                    if (canWrite) {
                                        Row {
                                            TextButton(onClick = {
                                                editing = t
                                                editWeekday = t.weekday
                                                editStart = formatTimeDisplay(t.startTime)
                                                editEnd = formatTimeDisplay(t.endTime)
                                            }) {
                                                Text(tr("trainingTimesTab.edit", "Bearbeiten"))
                                            }
                                            TextButton(onClick = { deleteTimeId = t.id }) {
                                                Text(tr("trainingTimesTab.delete", "Löschen"))
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        }
    }
    }

    if (editing != null) {
        val et = editing!!
        StableAlertDialog(
            onDismissRequest = { editing = null },
            title = { Text(tr("trainingTimesTab.editTime", "Trainingszeit bearbeiten")) },
            text = {
                Column {
                    Text(tr("trainingTimesTab.weekday", "Wochentag:"), style = MaterialTheme.typography.caption)
                    Box {
                        TextButton(onClick = { weekdayMenuEdit = true }) {
                            Text(trainingWeekdayLabel(languageCode, editWeekday))
                        }
                        DropdownMenu(expanded = weekdayMenuEdit, onDismissRequest = { weekdayMenuEdit = false }) {
                            (0..6).forEach { d ->
                                DropdownMenuItem(
                                    onClick = {
                                        editWeekday = d
                                        weekdayMenuEdit = false
                                    },
                                ) { Text(trainingWeekdayLabel(languageCode, d)) }
                            }
                        }
                    }
                    OutlinedTextField(
                        value = editStart,
                        onValueChange = { editStart = it },
                        label = { Text(tr("trainingTimesTab.from", "Von:")) },
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                    )
                    OutlinedTextField(
                        value = editEnd,
                        onValueChange = { editEnd = it },
                        label = { Text(tr("trainingTimesTab.to", "Bis:")) },
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        val s = parseClockToApi(editStart) ?: return@TextButton
                        val e = parseClockToApi(editEnd) ?: return@TextButton
                        if (s >= e) return@TextButton
                        scope.launch {
                            runCatching {
                                dependencies.membersManager.updateClubTrainingTime(
                                    clubId,
                                    et.id,
                                    UpdateTrainingTimeBody(weekday = editWeekday, startTime = s, endTime = e),
                                )
                                editing = null
                                refresh++
                            }.onFailure { error = it.message }
                        }
                    },
                ) { Text(tr("trainingTimesTab.save", "Speichern")) }
            },
            dismissButton = {
                TextButton(onClick = { editing = null }) { Text(tr("trainingTimesTab.cancel", "Abbrechen")) }
            },
        )
    }

    if (deleteTimeId != null) {
        val tid = deleteTimeId!!
        StableAlertDialog(
            onDismissRequest = { deleteTimeId = null },
            title = { Text(tr("trainingTimesTab.delete", "Löschen")) },
            text = { Text("Diese Trainingszeit wirklich löschen?") },
            confirmButton = {
                TextButton(
                    onClick = {
                        scope.launch {
                            runCatching {
                                dependencies.membersManager.deleteClubTrainingTime(clubId, tid)
                                deleteTimeId = null
                                refresh++
                            }.onFailure { error = it.message }
                        }
                    },
                ) { Text(tr("trainingTimesTab.delete", "Löschen")) }
            },
            dismissButton = {
                TextButton(onClick = { deleteTimeId = null }) { Text(tr("trainingTimesTab.cancel", "Abbrechen")) }
            },
        )
    }
}
