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.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.AlertDialog
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.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.repository.DiaryDateEntry
import de.trainingstagebuch.app.repository.DiaryActivityItem
import de.trainingstagebuch.app.repository.DiaryGroupItem
import de.trainingstagebuch.app.repository.DiaryPlanItem
import de.trainingstagebuch.app.repository.DiaryTagItem
import de.trainingstagebuch.app.repository.MemberItem
import de.trainingstagebuch.app.repository.MemberNoteItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.DiaryStatus
import de.trainingstagebuch.app.viewmodel.DiaryViewModel

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

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

            when (state.status) {
                DiaryStatus.Idle, DiaryStatus.Loading -> {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator()
                        Text(
                            text = stringResource(R.string.diary_loading),
                            modifier = Modifier.padding(top = 12.dp)
                        )
                    }
                }

                DiaryStatus.Error -> {
                    Button(onClick = diaryViewModel::load) {
                        Text(stringResource(R.string.home_retry))
                    }
                }

                DiaryStatus.Success -> {
                    DiaryContent(
                        dates = state.dates,
                        members = state.members,
                        participantMemberIds = state.participantMemberIds,
                        participantMapByMemberId = state.participantMapByMemberId,
                        participantGroupByMemberId = state.participantGroupByMemberId,
                        availableGroups = state.availableGroups,
                        newGroupName = state.newGroupName,
                        newGroupLead = state.newGroupLead,
                        newGroupActivity = state.newGroupActivity,
                        newGroupActivityGroupId = state.newGroupActivityGroupId,
                        editingGroupId = state.editingGroupId,
                        editingGroupName = state.editingGroupName,
                        editingGroupLead = state.editingGroupLead,
                        activities = state.activities,
                        planItems = state.planItems,
                        notes = state.notes,
                        availableTags = state.availableTags,
                        selectedDateTags = state.selectedDateTags,
                        selectedDateId = state.selectedDateId,
                        selectedNoteMemberId = state.selectedNoteMemberId,
                        newDate = state.newDate,
                        newTrainingStart = state.newTrainingStart,
                        newTrainingEnd = state.newTrainingEnd,
                        newActivityDescription = state.newActivityDescription,
                        newNoteContent = state.newNoteContent,
                        newTagName = state.newTagName,
                        newPlanActivity = state.newPlanActivity,
                        editingPlanItemId = state.editingPlanItemId,
                        editingPlanActivity = state.editingPlanActivity,
                        activityParticipantIdsByActivityId = state.activityParticipantIdsByActivityId,
                        accidents = state.accidents,
                        newAccident = state.newAccident,
                        showQuickAddDialog = state.showQuickAddDialog,
                        quickAddFirstName = state.quickAddFirstName,
                        quickAddLastName = state.quickAddLastName,
                        quickAddBirthDate = state.quickAddBirthDate,
                        quickAddGender = state.quickAddGender,
                        statsMemberId = state.statsMemberId,
                        memberActivityStats = state.memberActivityStats,
                        memberLastParticipations = state.memberLastParticipations,
                        createLoading = state.createLoading,
                        selectedTrainingStart = state.selectedTrainingStart,
                        selectedTrainingEnd = state.selectedTrainingEnd,
                        actionLoading = state.actionLoading,
                        onSelectDate = diaryViewModel::onSelectDate,
                        onNewDateChanged = diaryViewModel::onNewDateChanged,
                        onTrainingStartChanged = diaryViewModel::onTrainingStartChanged,
                        onTrainingEndChanged = diaryViewModel::onTrainingEndChanged,
                        onNewActivityDescriptionChanged = diaryViewModel::onNewActivityDescriptionChanged,
                        onNewTagNameChanged = diaryViewModel::onNewTagNameChanged,
                        onNewPlanActivityChanged = diaryViewModel::onNewPlanActivityChanged,
                        onStartEditPlanItem = diaryViewModel::startEditPlanItem,
                        onEditingPlanActivityChanged = diaryViewModel::onEditingPlanActivityChanged,
                        onCancelEditPlanItem = diaryViewModel::cancelEditPlanItem,
                        onSelectedNoteMemberChanged = diaryViewModel::onSelectedNoteMemberChanged,
                        onNewNoteContentChanged = diaryViewModel::onNewNoteContentChanged,
                        onSelectedTrainingStartChanged = diaryViewModel::onSelectedTrainingStartChanged,
                        onSelectedTrainingEndChanged = diaryViewModel::onSelectedTrainingEndChanged,
                        onCreateDate = diaryViewModel::createDate,
                        onAddActivity = diaryViewModel::addActivity,
                        onCreateTagAndAdd = diaryViewModel::createTagAndAddToSelectedDate,
                        onAddExistingTag = diaryViewModel::addExistingTagToSelectedDate,
                        onRemoveTag = diaryViewModel::removeTagFromSelectedDate,
                        onAddPlanItem = diaryViewModel::addPlanItem,
                        onSaveEditPlanItem = diaryViewModel::saveEditPlanItem,
                        onDeletePlanItem = diaryViewModel::deletePlanItem,
                        onMovePlanItemUp = diaryViewModel::movePlanItemUp,
                        onMovePlanItemDown = diaryViewModel::movePlanItemDown,
                        onAddNote = diaryViewModel::addNote,
                        onReload = diaryViewModel::load,
                        onUpdateSelectedTimes = diaryViewModel::updateSelectedDateTimes,
                        onDeleteSelectedDate = diaryViewModel::deleteSelectedDate,
                        onDeleteNotAllowed = diaryViewModel::notifyDeleteNotAllowed,
                        onToggleParticipant = diaryViewModel::toggleParticipant,
                        onParticipantGroupChanged = diaryViewModel::onParticipantGroupChanged,
                        onNewGroupNameChanged = diaryViewModel::onNewGroupNameChanged,
                        onNewGroupLeadChanged = diaryViewModel::onNewGroupLeadChanged,
                        onNewGroupActivityChanged = diaryViewModel::onNewGroupActivityChanged,
                        onNewGroupActivityGroupChanged = diaryViewModel::onNewGroupActivityGroupChanged,
                        onCreateGroup = diaryViewModel::createGroup,
                        onAddGroupActivity = diaryViewModel::addGroupActivity,
                        onStartEditGroup = diaryViewModel::startEditGroup,
                        onEditingGroupNameChanged = diaryViewModel::onEditingGroupNameChanged,
                        onEditingGroupLeadChanged = diaryViewModel::onEditingGroupLeadChanged,
                        onSaveEditGroup = diaryViewModel::saveEditGroup,
                        onCancelEditGroup = diaryViewModel::cancelEditGroup,
                        onDeleteGroup = diaryViewModel::deleteGroup,
                        onDeleteNote = diaryViewModel::deleteNote,
                        onToggleActivityMember = diaryViewModel::toggleActivityMember,
                        onOpenQuickAddDialog = diaryViewModel::openQuickAddDialog,
                        onCloseQuickAddDialog = diaryViewModel::closeQuickAddDialog,
                        onQuickAddFirstNameChanged = diaryViewModel::onQuickAddFirstNameChanged,
                        onQuickAddLastNameChanged = diaryViewModel::onQuickAddLastNameChanged,
                        onQuickAddBirthDateChanged = diaryViewModel::onQuickAddBirthDateChanged,
                        onQuickAddGenderChanged = diaryViewModel::onQuickAddGenderChanged,
                        onCreateAndAddMember = diaryViewModel::createAndAddMember,
                        onNewAccidentChanged = diaryViewModel::onNewAccidentChanged,
                        onSaveAccident = diaryViewModel::saveAccident,
                        onRefreshAccidents = diaryViewModel::refreshAccidents,
                        onOpenStatsForMember = diaryViewModel::openStatsForMember,
                        onDismissStatsDialog = diaryViewModel::dismissStatsDialog
                    )
                }
            }
        }
    }
}

@Composable
private fun DiaryContent(
    dates: List<DiaryDateEntry>,
    members: List<MemberItem>,
    participantMemberIds: List<String>,
    participantMapByMemberId: Map<String, String>,
    participantGroupByMemberId: Map<String, String?>,
    availableGroups: List<DiaryGroupItem>,
    newGroupName: String,
    newGroupLead: String,
    newGroupActivity: String,
    newGroupActivityGroupId: String,
    editingGroupId: String?,
    editingGroupName: String,
    editingGroupLead: String,
    activities: List<DiaryActivityItem>,
    planItems: List<DiaryPlanItem>,
    notes: List<MemberNoteItem>,
    availableTags: List<DiaryTagItem>,
    selectedDateTags: List<DiaryTagItem>,
    selectedDateId: String?,
    selectedNoteMemberId: String?,
    newDate: String,
    newTrainingStart: String,
    newTrainingEnd: String,
    newActivityDescription: String,
    newNoteContent: String,
    newTagName: String,
    newPlanActivity: String,
    editingPlanItemId: String?,
    editingPlanActivity: String,
    activityParticipantIdsByActivityId: Map<String, Set<String>>,
    accidents: List<de.trainingstagebuch.app.repository.DiaryAccidentItem>,
    newAccident: String,
    showQuickAddDialog: Boolean,
    quickAddFirstName: String,
    quickAddLastName: String,
    quickAddBirthDate: String,
    quickAddGender: String,
    statsMemberId: String?,
    memberActivityStats: List<de.trainingstagebuch.app.repository.MemberActivityStatItem>,
    memberLastParticipations: List<de.trainingstagebuch.app.repository.MemberParticipationItem>,
    createLoading: Boolean,
    selectedTrainingStart: String,
    selectedTrainingEnd: String,
    actionLoading: Boolean,
    onSelectDate: (String) -> Unit,
    onNewDateChanged: (String) -> Unit,
    onTrainingStartChanged: (String) -> Unit,
    onTrainingEndChanged: (String) -> Unit,
    onNewActivityDescriptionChanged: (String) -> Unit,
    onNewTagNameChanged: (String) -> Unit,
    onNewPlanActivityChanged: (String) -> Unit,
    onStartEditPlanItem: (String, String) -> Unit,
    onEditingPlanActivityChanged: (String) -> Unit,
    onCancelEditPlanItem: () -> Unit,
    onSelectedNoteMemberChanged: (String) -> Unit,
    onNewNoteContentChanged: (String) -> Unit,
    onSelectedTrainingStartChanged: (String) -> Unit,
    onSelectedTrainingEndChanged: (String) -> Unit,
    onCreateDate: () -> Unit,
    onAddActivity: () -> Unit,
    onCreateTagAndAdd: () -> Unit,
    onAddExistingTag: (String) -> Unit,
    onRemoveTag: (String) -> Unit,
    onAddPlanItem: () -> Unit,
    onSaveEditPlanItem: () -> Unit,
    onDeletePlanItem: (String) -> Unit,
    onMovePlanItemUp: (String) -> Unit,
    onMovePlanItemDown: (String) -> Unit,
    onAddNote: () -> Unit,
    onReload: () -> Unit,
    onUpdateSelectedTimes: () -> Unit,
    onDeleteSelectedDate: () -> Unit,
    onDeleteNotAllowed: () -> Unit,
    onToggleParticipant: (String) -> Unit,
    onParticipantGroupChanged: (String, String?) -> Unit,
    onNewGroupNameChanged: (String) -> Unit,
    onNewGroupLeadChanged: (String) -> Unit,
    onNewGroupActivityChanged: (String) -> Unit,
    onNewGroupActivityGroupChanged: (String) -> Unit,
    onCreateGroup: () -> Unit,
    onAddGroupActivity: () -> Unit,
    onStartEditGroup: (String, String, String) -> Unit,
    onEditingGroupNameChanged: (String) -> Unit,
    onEditingGroupLeadChanged: (String) -> Unit,
    onSaveEditGroup: () -> Unit,
    onCancelEditGroup: () -> Unit,
    onDeleteGroup: (String) -> Unit,
    onDeleteNote: (String) -> Unit,
    onToggleActivityMember: (String, String) -> Unit,
    onOpenQuickAddDialog: () -> Unit,
    onCloseQuickAddDialog: () -> Unit,
    onQuickAddFirstNameChanged: (String) -> Unit,
    onQuickAddLastNameChanged: (String) -> Unit,
    onQuickAddBirthDateChanged: (String) -> Unit,
    onQuickAddGenderChanged: (String) -> Unit,
    onCreateAndAddMember: () -> Unit,
    onNewAccidentChanged: (String) -> Unit,
    onSaveAccident: () -> Unit,
    onRefreshAccidents: () -> Unit,
    onOpenStatsForMember: (String) -> Unit,
    onDismissStatsDialog: () -> Unit
) {
    val participantMembers = members.filter { participantMemberIds.contains(it.id) }
    var expandedGroupMemberId by remember { mutableStateOf<String?>(null) }
    var showDeleteConfirm by remember { mutableStateOf(false) }
    val canDeleteSelectedDate = selectedDateId != null &&
        planItems.isEmpty() &&
        participantMemberIds.isEmpty() &&
        activities.isEmpty() &&
        notes.isEmpty()
    OutlinedTextField(
        value = newDate,
        onValueChange = onNewDateChanged,
        label = { Text(stringResource(R.string.diary_new_date_label)) },
        singleLine = true,
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 8.dp)
    )
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        OutlinedTextField(
            value = newTrainingStart,
            onValueChange = onTrainingStartChanged,
            label = { Text(stringResource(R.string.diary_training_start_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
        OutlinedTextField(
            value = newTrainingEnd,
            onValueChange = onTrainingEndChanged,
            label = { Text(stringResource(R.string.diary_training_end_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
    }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp, bottom = 12.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Button(
            onClick = onCreateDate,
            enabled = !createLoading && !actionLoading
        ) {
            Text(stringResource(R.string.diary_create_button))
        }
        Button(
            onClick = onReload,
            enabled = !createLoading && !actionLoading
        ) {
            Text(stringResource(R.string.home_retry))
        }
    }

    if (dates.isEmpty()) {
        Text(text = stringResource(R.string.diary_empty))
        return
    }

    Text(
        text = stringResource(R.string.diary_selected_times_title),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(bottom = 6.dp)
    )
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        OutlinedTextField(
            value = selectedTrainingStart,
            onValueChange = onSelectedTrainingStartChanged,
            label = { Text(stringResource(R.string.diary_training_start_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
        OutlinedTextField(
            value = selectedTrainingEnd,
            onValueChange = onSelectedTrainingEndChanged,
            label = { Text(stringResource(R.string.diary_training_end_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
    }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp, bottom = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Button(
            onClick = onUpdateSelectedTimes,
            enabled = selectedDateId != null && !createLoading && !actionLoading
        ) {
            Text(stringResource(R.string.diary_update_times_button))
        }
        Button(
            onClick = {
                if (canDeleteSelectedDate) {
                    showDeleteConfirm = true
                } else {
                    onDeleteNotAllowed()
                }
            },
            enabled = selectedDateId != null && !createLoading && !actionLoading
        ) {
            Text(stringResource(R.string.diary_delete_button))
        }
    }

    Text(
        text = stringResource(R.string.diary_participants_title, participantMemberIds.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    Button(
        onClick = onOpenQuickAddDialog,
        enabled = selectedDateId != null && !createLoading && !actionLoading,
        modifier = Modifier.padding(bottom = 6.dp)
    ) {
        Text(stringResource(R.string.diary_quick_add_button))
    }
    if (members.isEmpty()) {
        Text(text = stringResource(R.string.diary_no_members))
    } else {
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 8.dp),
            verticalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            items(members, key = { it.id }) { member ->
                val isParticipant = participantMemberIds.contains(member.id)
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = member.displayName,
                        modifier = Modifier.weight(1f)
                    )
                    if (isParticipant) {
                        Button(
                            onClick = { onOpenStatsForMember(member.id) },
                            enabled = !createLoading && !actionLoading,
                            modifier = Modifier.padding(end = 4.dp)
                        ) {
                            Text(stringResource(R.string.diary_stats_button))
                        }
                    }
                    if (isParticipant) {
                        val currentGroupId = participantGroupByMemberId[member.id]
                        val currentGroupName = availableGroups
                            .firstOrNull { it.id == currentGroupId }
                            ?.name
                            ?: stringResource(R.string.diary_group_none)
                        Button(
                            onClick = { expandedGroupMemberId = member.id },
                            enabled = selectedDateId != null && !createLoading && !actionLoading,
                            modifier = Modifier.padding(end = 4.dp)
                        ) {
                            Text(currentGroupName)
                        }
                        DropdownMenu(
                            expanded = expandedGroupMemberId == member.id,
                            onDismissRequest = { expandedGroupMemberId = null }
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.diary_group_none)) },
                                onClick = {
                                    expandedGroupMemberId = null
                                    onParticipantGroupChanged(member.id, null)
                                }
                            )
                            availableGroups.forEach { group ->
                                DropdownMenuItem(
                                    text = { Text(group.name) },
                                    onClick = {
                                        expandedGroupMemberId = null
                                        onParticipantGroupChanged(member.id, group.id)
                                    }
                                )
                            }
                        }
                    }
                    Button(
                        onClick = { onToggleParticipant(member.id) },
                        enabled = selectedDateId != null && !createLoading && !actionLoading
                    ) {
                        Text(
                            text = if (isParticipant) {
                                stringResource(R.string.diary_remove_participant_button)
                            } else {
                                stringResource(R.string.diary_add_participant_button)
                            }
                        )
                    }
                }
            }
        }
    }

    Text(
        text = stringResource(R.string.diary_groups_title, availableGroups.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        OutlinedTextField(
            value = newGroupName,
            onValueChange = onNewGroupNameChanged,
            label = { Text(stringResource(R.string.diary_group_name_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
        OutlinedTextField(
            value = newGroupLead,
            onValueChange = onNewGroupLeadChanged,
            label = { Text(stringResource(R.string.diary_group_lead_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
    }
    Button(
        onClick = onCreateGroup,
        enabled = selectedDateId != null && !createLoading && !actionLoading,
        modifier = Modifier.padding(top = 6.dp, bottom = 6.dp)
    ) {
        Text(stringResource(R.string.diary_group_create_button))
    }
    if (availableGroups.isEmpty()) {
        Text(
            text = stringResource(R.string.diary_groups_empty),
            modifier = Modifier.padding(bottom = 8.dp)
        )
    } else {
        availableGroups.forEach { group ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (editingGroupId == group.id) {
                    OutlinedTextField(
                        value = editingGroupName,
                        onValueChange = onEditingGroupNameChanged,
                        label = { Text(stringResource(R.string.diary_group_name_label)) },
                        singleLine = true,
                        modifier = Modifier
                            .weight(1f)
                            .padding(end = 6.dp)
                    )
                    OutlinedTextField(
                        value = editingGroupLead,
                        onValueChange = onEditingGroupLeadChanged,
                        label = { Text(stringResource(R.string.diary_group_lead_label)) },
                        singleLine = true,
                        modifier = Modifier
                            .weight(1f)
                            .padding(end = 6.dp)
                    )
                    Button(
                        onClick = onSaveEditGroup,
                        enabled = !createLoading && !actionLoading,
                        modifier = Modifier.padding(end = 4.dp)
                    ) {
                        Text(stringResource(R.string.diary_group_save_button))
                    }
                    Button(
                        onClick = onCancelEditGroup,
                        enabled = !createLoading && !actionLoading
                    ) {
                        Text(stringResource(R.string.diary_group_cancel_button))
                    }
                } else {
                    Text(
                        text = "${group.name} (${group.lead})",
                        modifier = Modifier.weight(1f)
                    )
                    Button(
                        onClick = { onStartEditGroup(group.id, group.name, group.lead) },
                        enabled = !createLoading && !actionLoading,
                        modifier = Modifier.padding(end = 4.dp)
                    ) {
                        Text(stringResource(R.string.diary_group_edit_button))
                    }
                    Button(
                        onClick = { onDeleteGroup(group.id) },
                        enabled = !createLoading && !actionLoading
                    ) {
                        Text(stringResource(R.string.diary_group_delete_button))
                    }
                }
            }
        }
    }

    Text(
        text = stringResource(R.string.diary_activities_title, activities.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    OutlinedTextField(
        value = newActivityDescription,
        onValueChange = onNewActivityDescriptionChanged,
        label = { Text(stringResource(R.string.diary_activity_input_label)) },
        singleLine = true,
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 6.dp)
    )
    Button(
        onClick = onAddActivity,
        enabled = selectedDateId != null && !createLoading && !actionLoading,
        modifier = Modifier.padding(bottom = 6.dp)
    ) {
        Text(stringResource(R.string.diary_add_activity_button))
    }
    if (activities.isEmpty()) {
        Text(
            text = stringResource(R.string.diary_activities_empty),
            modifier = Modifier.padding(bottom = 8.dp)
        )
    } else {
        activities.forEach { activity ->
            Text(
                text = "• ${activity.description}",
                modifier = Modifier.padding(bottom = 2.dp)
            )
        }
    }

    Text(
        text = stringResource(R.string.diary_tags_title, selectedDateTags.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    OutlinedTextField(
        value = newTagName,
        onValueChange = onNewTagNameChanged,
        label = { Text(stringResource(R.string.diary_new_tag_input_label)) },
        singleLine = true,
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 6.dp)
    )
    Button(
        onClick = onCreateTagAndAdd,
        enabled = selectedDateId != null && !createLoading && !actionLoading,
        modifier = Modifier.padding(bottom = 6.dp)
    ) {
        Text(stringResource(R.string.diary_create_tag_button))
    }
    if (availableTags.isEmpty()) {
        Text(
            text = stringResource(R.string.diary_no_tags_available),
            modifier = Modifier.padding(bottom = 8.dp)
        )
    } else {
        availableTags.forEach { tag ->
            val selected = selectedDateTags.any { it.id == tag.id }
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = tag.name,
                    modifier = Modifier.weight(1f)
                )
                Button(
                    onClick = {
                        if (selected) onRemoveTag(tag.id) else onAddExistingTag(tag.id)
                    },
                    enabled = selectedDateId != null && !createLoading && !actionLoading
                ) {
                    Text(
                        text = if (selected) {
                            stringResource(R.string.diary_remove_tag_button)
                        } else {
                            stringResource(R.string.diary_add_tag_button)
                        }
                    )
                }
            }
        }
    }

    Text(
        text = stringResource(R.string.diary_plan_title, planItems.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    Text(
        text = stringResource(R.string.diary_group_activity_title),
        style = MaterialTheme.typography.titleSmall,
        modifier = Modifier.padding(bottom = 4.dp)
    )
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        OutlinedTextField(
            value = newGroupActivity,
            onValueChange = onNewGroupActivityChanged,
            label = { Text(stringResource(R.string.diary_group_activity_input_label)) },
            singleLine = true,
            modifier = Modifier.weight(1f)
        )
        var groupSelectExpanded by remember { mutableStateOf(false) }
        val selectedGroupLabel = availableGroups.firstOrNull { it.id == newGroupActivityGroupId }?.name
            ?: stringResource(R.string.diary_group_none)
        Button(
            onClick = { groupSelectExpanded = true },
            enabled = !createLoading && !actionLoading
        ) {
            Text(selectedGroupLabel)
        }
        DropdownMenu(
            expanded = groupSelectExpanded,
            onDismissRequest = { groupSelectExpanded = false }
        ) {
            availableGroups.forEach { group ->
                DropdownMenuItem(
                    text = { Text(group.name) },
                    onClick = {
                        onNewGroupActivityGroupChanged(group.id)
                        groupSelectExpanded = false
                    }
                )
            }
        }
    }
    Button(
        onClick = onAddGroupActivity,
        enabled = selectedDateId != null && !createLoading && !actionLoading,
        modifier = Modifier.padding(top = 6.dp, bottom = 6.dp)
    ) {
        Text(stringResource(R.string.diary_group_activity_add_button))
    }
    OutlinedTextField(
        value = newPlanActivity,
        onValueChange = onNewPlanActivityChanged,
        label = { Text(stringResource(R.string.diary_plan_new_activity_label)) },
        singleLine = true,
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 6.dp)
    )
    Button(
        onClick = onAddPlanItem,
        enabled = selectedDateId != null && !createLoading && !actionLoading,
        modifier = Modifier.padding(bottom = 6.dp)
    ) {
        Text(stringResource(R.string.diary_plan_add_button))
    }
    if (planItems.isEmpty()) {
        Text(
            text = stringResource(R.string.diary_plan_empty),
            modifier = Modifier.padding(bottom = 8.dp)
        )
    } else {
        planItems.forEachIndexed { index, item ->
            val itemText = if (item.isTimeblock) {
                stringResource(R.string.diary_plan_timeblock_label)
            } else {
                item.activity
            }
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (editingPlanItemId == item.id) {
                    OutlinedTextField(
                        value = editingPlanActivity,
                        onValueChange = onEditingPlanActivityChanged,
                        label = { Text(stringResource(R.string.diary_plan_new_activity_label)) },
                        singleLine = true,
                        modifier = Modifier
                            .weight(1f)
                            .padding(end = 6.dp)
                    )
                    Button(
                        onClick = onSaveEditPlanItem,
                        enabled = !createLoading && !actionLoading,
                        modifier = Modifier.padding(end = 4.dp)
                    ) {
                        Text(stringResource(R.string.diary_plan_save_button))
                    }
                    Button(
                        onClick = onCancelEditPlanItem,
                        enabled = !createLoading && !actionLoading
                    ) {
                        Text(stringResource(R.string.diary_plan_cancel_button))
                    }
                } else {
                    Text(
                        text = "• $itemText",
                        modifier = Modifier.weight(1f)
                    )
                    Button(
                        onClick = { onMovePlanItemUp(item.id) },
                        enabled = index > 0 && !createLoading && !actionLoading,
                        modifier = Modifier.padding(end = 4.dp)
                    ) {
                        Text(stringResource(R.string.diary_plan_up_button))
                    }
                    Button(
                        onClick = { onMovePlanItemDown(item.id) },
                        enabled = index < planItems.lastIndex && !createLoading && !actionLoading,
                        modifier = Modifier.padding(end = 4.dp)
                    ) {
                        Text(stringResource(R.string.diary_plan_down_button))
                    }
                    if (!item.isTimeblock) {
                        Button(
                            onClick = { onStartEditPlanItem(item.id, item.activity) },
                            enabled = !createLoading && !actionLoading,
                            modifier = Modifier.padding(end = 4.dp)
                        ) {
                            Text(stringResource(R.string.diary_plan_edit_button))
                        }
                    }
                    Button(
                        onClick = { onDeletePlanItem(item.id) },
                        enabled = !createLoading && !actionLoading
                    ) {
                        Text(stringResource(R.string.diary_plan_delete_button))
                    }
                }
            }
            if (!item.isTimeblock && participantMembers.isNotEmpty()) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 8.dp, bottom = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    participantMembers.forEach { member ->
                        val assigned = activityParticipantIdsByActivityId[item.id]
                            ?.contains(participantMapByMemberId[member.id])
                            ?: false
                        Button(
                            onClick = { onToggleActivityMember(item.id, member.id) },
                            enabled = !createLoading && !actionLoading
                        ) {
                            Text(
                                if (assigned) {
                                    "${member.displayName} ✓"
                                } else {
                                    member.displayName
                                }
                            )
                        }
                    }
                }
            }
        }
    }

    Text(
        text = stringResource(R.string.diary_notes_title, notes.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    if (participantMembers.isEmpty()) {
        Text(
            text = stringResource(R.string.diary_no_participants_for_notes),
            modifier = Modifier.padding(bottom = 8.dp)
        )
    } else {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 6.dp),
            horizontalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            participantMembers.forEach { member ->
                Button(
                    onClick = { onSelectedNoteMemberChanged(member.id) },
                    enabled = !createLoading && !actionLoading
                ) {
                    Text(text = member.displayName)
                }
            }
        }
        OutlinedTextField(
            value = newNoteContent,
            onValueChange = onNewNoteContentChanged,
            label = { Text(stringResource(R.string.diary_note_input_label)) },
            singleLine = true,
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 6.dp)
        )
        Button(
            onClick = onAddNote,
            enabled = selectedNoteMemberId != null && !createLoading && !actionLoading,
            modifier = Modifier.padding(bottom = 6.dp)
        ) {
            Text(stringResource(R.string.diary_add_note_button))
        }
        if (notes.isEmpty()) {
            Text(
                text = stringResource(R.string.diary_notes_empty),
                modifier = Modifier.padding(bottom = 8.dp)
            )
        } else {
            notes.forEach { note ->
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = note.content,
                        modifier = Modifier.weight(1f)
                    )
                    Button(
                        onClick = { onDeleteNote(note.id) },
                        enabled = !createLoading && !actionLoading
                    ) {
                        Text(stringResource(R.string.diary_delete_note_button))
                    }
                }
            }
        }
    }

    Text(
        text = stringResource(R.string.diary_accidents_title, accidents.size),
        style = MaterialTheme.typography.titleMedium,
        modifier = Modifier.padding(top = 4.dp, bottom = 6.dp)
    )
    OutlinedTextField(
        value = newAccident,
        onValueChange = onNewAccidentChanged,
        label = { Text(stringResource(R.string.diary_accident_input_label)) },
        singleLine = true,
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 6.dp)
    )
    Row(
        modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Button(
            onClick = onSaveAccident,
            enabled = selectedDateId != null && !createLoading && !actionLoading
        ) { Text(stringResource(R.string.diary_accident_save_button)) }
        Button(
            onClick = onRefreshAccidents,
            enabled = selectedDateId != null && !createLoading && !actionLoading
        ) { Text(stringResource(R.string.home_retry)) }
    }
    accidents.forEach { item ->
        Text(stringResource(R.string.diary_accident_item_value, item.accident))
    }

    LazyColumn(modifier = Modifier.fillMaxSize()) {
        items(dates, key = { it.id }) { item ->
            val selected = item.id == selectedDateId
            val times = listOf(item.trainingStart, item.trainingEnd)
                .filterNotNull()
                .filter { it.isNotBlank() }
                .joinToString(" - ")
                .ifBlank { "-" }
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onSelectDate(item.id) }
                    .padding(vertical = 8.dp)
            ) {
                Text(
                    text = item.date,
                    style = if (selected) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyLarge,
                    color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                )
                Text(
                    text = stringResource(R.string.diary_times_value, times),
                    style = MaterialTheme.typography.bodySmall
                )
            }
        }
    }

    if (showDeleteConfirm) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirm = false },
            title = { Text(stringResource(R.string.diary_confirm_delete_title)) },
            text = { Text(stringResource(R.string.diary_confirm_delete_message)) },
            confirmButton = {
                TextButton(
                    onClick = {
                        showDeleteConfirm = false
                        onDeleteSelectedDate()
                    }
                ) {
                    Text(stringResource(R.string.diary_confirm_delete_confirm))
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirm = false }) {
                    Text(stringResource(R.string.diary_confirm_delete_cancel))
                }
            }
        )
    }

    if (showQuickAddDialog) {
        AlertDialog(
            onDismissRequest = onCloseQuickAddDialog,
            title = { Text(stringResource(R.string.diary_quick_add_title)) },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    OutlinedTextField(
                        value = quickAddFirstName,
                        onValueChange = onQuickAddFirstNameChanged,
                        label = { Text(stringResource(R.string.diary_quick_add_firstname_label)) },
                        singleLine = true
                    )
                    OutlinedTextField(
                        value = quickAddLastName,
                        onValueChange = onQuickAddLastNameChanged,
                        label = { Text(stringResource(R.string.diary_quick_add_lastname_label)) },
                        singleLine = true
                    )
                    OutlinedTextField(
                        value = quickAddBirthDate,
                        onValueChange = onQuickAddBirthDateChanged,
                        label = { Text(stringResource(R.string.diary_quick_add_birthdate_label)) },
                        singleLine = true
                    )
                    OutlinedTextField(
                        value = quickAddGender,
                        onValueChange = onQuickAddGenderChanged,
                        label = { Text(stringResource(R.string.diary_quick_add_gender_label)) },
                        singleLine = true
                    )
                }
            },
            confirmButton = {
                TextButton(onClick = onCreateAndAddMember) {
                    Text(stringResource(R.string.diary_quick_add_confirm))
                }
            },
            dismissButton = {
                TextButton(onClick = onCloseQuickAddDialog) {
                    Text(stringResource(R.string.diary_quick_add_cancel))
                }
            }
        )
    }

    if (statsMemberId != null) {
        AlertDialog(
            onDismissRequest = onDismissStatsDialog,
            title = { Text(stringResource(R.string.diary_stats_title)) },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(stringResource(R.string.diary_stats_recent_title))
                    if (memberLastParticipations.isEmpty()) {
                        Text(stringResource(R.string.diary_stats_empty))
                    } else {
                        memberLastParticipations.forEach { participation ->
                            Text(
                                stringResource(
                                    R.string.diary_participation_item_value,
                                    participation.date,
                                    participation.activity
                                )
                            )
                        }
                    }
                    Text(stringResource(R.string.diary_stats_activity_title))
                    if (memberActivityStats.isEmpty()) {
                        Text(stringResource(R.string.diary_stats_empty))
                    } else {
                        memberActivityStats.forEach { stat ->
                            Text(stringResource(R.string.diary_stat_item_value, stat.activity, stat.count))
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = onDismissStatsDialog) {
                    Text(stringResource(R.string.diary_stats_close))
                }
            }
        )
    }
}
