package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.clickable
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
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.PredefinedActivityItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.PredefinedActivitiesViewModel

private enum class PredefinedConfirmAction {
    Merge,
    Deduplicate,
    DeleteImage
}

@Composable
fun PredefinedActivitiesScreen(
    viewModel: PredefinedActivitiesViewModel = viewModel()
) {
    val state by viewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedError by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    var mergeMenuExpanded by remember { mutableStateOf(false) }
    var targetMenuExpanded by remember { mutableStateOf(false) }

    var confirmAction by remember { mutableStateOf<PredefinedConfirmAction?>(null) }
    var pendingDeleteImageId by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(state.errorMessage, state.successMessage) {
        state.errorMessage?.let {
            dismissedError = null
            snackbarHostState.showSnackbar(it.resolve(context))
        }
        state.successMessage?.let {
            snackbarHostState.showSnackbar(it.resolve(context))
        }
    }

    val listItems = if (state.searchQuery.trim().length >= 2) state.searchResults else state.activities
    val sourceLabel = state.activities.firstOrNull { it.id == state.mergeSourceId }?.formatLabel().orEmpty()
    val targetLabel = state.activities.firstOrNull { it.id == state.mergeTargetId }?.formatLabel().orEmpty()

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.predefined_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
        ) {
            Text(
                text = stringResource(R.string.predefined_title),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 8.dp)
            )

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

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Button(onClick = viewModel::startCreate) {
                    Text(stringResource(R.string.predefined_new))
                }
                Button(onClick = viewModel::load) {
                    Text(stringResource(R.string.predefined_reload))
                }
                Button(
                    onClick = { confirmAction = PredefinedConfirmAction.Deduplicate },
                    enabled = !state.actionLoading
                ) {
                    Text(stringResource(R.string.predefined_deduplicate_button))
                }
            }

            OutlinedTextField(
                value = state.searchQuery,
                onValueChange = viewModel::onSearchQueryChanged,
                label = { Text(stringResource(R.string.predefined_search_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
            )
            if (state.searchQuery.isNotBlank()) {
                TextButton(onClick = viewModel::clearSearch) {
                    Text(stringResource(R.string.predefined_clear_search))
                }
            }

            Text(
                text = stringResource(R.string.predefined_merge_title),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(top = 6.dp)
            )
            Row(
                modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Box(modifier = Modifier.weight(1f)) {
                    Button(onClick = { mergeMenuExpanded = true }, modifier = Modifier.fillMaxWidth()) {
                        Text(
                            sourceLabel.ifBlank { stringResource(R.string.predefined_merge_source_hint) },
                            maxLines = 1
                        )
                    }
                    DropdownMenu(expanded = mergeMenuExpanded, onDismissRequest = { mergeMenuExpanded = false }) {
                        state.activities.forEach { item ->
                            DropdownMenuItem(
                                text = { Text(item.formatLabel()) },
                                onClick = {
                                    viewModel.onMergeSourceChanged(item.id)
                                    mergeMenuExpanded = false
                                }
                            )
                        }
                    }
                }
                Box(modifier = Modifier.weight(1f)) {
                    Button(onClick = { targetMenuExpanded = true }, modifier = Modifier.fillMaxWidth()) {
                        Text(
                            targetLabel.ifBlank { stringResource(R.string.predefined_merge_target_hint) },
                            maxLines = 1
                        )
                    }
                    DropdownMenu(expanded = targetMenuExpanded, onDismissRequest = { targetMenuExpanded = false }) {
                        state.activities.forEach { item ->
                            DropdownMenuItem(
                                text = { Text(item.formatLabel()) },
                                onClick = {
                                    viewModel.onMergeTargetChanged(item.id)
                                    targetMenuExpanded = false
                                }
                            )
                        }
                    }
                }
            }
            Button(
                onClick = { confirmAction = PredefinedConfirmAction.Merge },
                enabled = !state.actionLoading && state.mergeSourceId.isNotBlank() && state.mergeTargetId.isNotBlank() && state.mergeSourceId != state.mergeTargetId,
                modifier = Modifier.padding(top = 6.dp)
            ) {
                Text(stringResource(R.string.predefined_merge_button))
            }

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

            if (!state.loading && listItems.isEmpty()) {
                Button(onClick = viewModel::load) {
                    Text(stringResource(R.string.common_retry))
                }
            }

            LazyColumn(
                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                items(listItems, key = { it.id }) { item ->
                    ActivityListRow(
                        item = item,
                        selected = state.selectedActivityId == item.id,
                        onClick = { viewModel.selectActivity(item.id) }
                    )
                }
            }

            val model = state.editModel
            if (model != null) {
                Text(
                    text = stringResource(R.string.predefined_editor_title),
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(top = 8.dp, bottom = 6.dp)
                )
                OutlinedTextField(
                    value = model.name,
                    onValueChange = viewModel::onEditNameChanged,
                    label = { Text(stringResource(R.string.predefined_name_label)) },
                    modifier = Modifier.fillMaxWidth()
                )
                OutlinedTextField(
                    value = model.code,
                    onValueChange = viewModel::onEditCodeChanged,
                    label = { Text(stringResource(R.string.predefined_code_label)) },
                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
                )
                OutlinedTextField(
                    value = model.duration,
                    onValueChange = viewModel::onEditDurationChanged,
                    label = { Text(stringResource(R.string.predefined_duration_label)) },
                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
                )
                OutlinedTextField(
                    value = model.durationText,
                    onValueChange = viewModel::onEditDurationTextChanged,
                    label = { Text(stringResource(R.string.predefined_duration_text_label)) },
                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
                )
                OutlinedTextField(
                    value = model.description,
                    onValueChange = viewModel::onEditDescriptionChanged,
                    label = { Text(stringResource(R.string.predefined_description_label)) },
                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
                )
                OutlinedTextField(
                    value = model.imageLink,
                    onValueChange = viewModel::onEditImageLinkChanged,
                    label = { Text(stringResource(R.string.predefined_image_link_label)) },
                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
                )
                OutlinedTextField(
                    value = model.drawingData,
                    onValueChange = viewModel::onEditDrawingDataChanged,
                    label = { Text(stringResource(R.string.predefined_drawing_data_label)) },
                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
                )
                Row(
                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(
                        onClick = viewModel::save,
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.common_save))
                    }
                    Button(
                        onClick = viewModel::cancelEdit,
                        enabled = !state.actionLoading
                    ) {
                        Text(stringResource(R.string.predefined_cancel))
                    }
                }
                if (model.images.isNotEmpty()) {
                    Text(
                        text = stringResource(R.string.predefined_images_title),
                        style = MaterialTheme.typography.titleSmall,
                        modifier = Modifier.padding(top = 8.dp)
                    )
                    model.images.forEach { image ->
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(top = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(image.imageId)
                            Button(
                                onClick = {
                                    pendingDeleteImageId = image.imageId
                                    confirmAction = PredefinedConfirmAction.DeleteImage
                                },
                                enabled = !state.actionLoading
                            ) {
                                Text(stringResource(R.string.predefined_delete_image))
                            }
                        }
                    }
                }
            }
        }
    }

    val action = confirmAction
    if (action != null) {
        val title = when (action) {
            PredefinedConfirmAction.Merge -> stringResource(R.string.predefined_confirm_merge_title)
            PredefinedConfirmAction.Deduplicate -> stringResource(R.string.predefined_confirm_deduplicate_title)
            PredefinedConfirmAction.DeleteImage -> stringResource(R.string.predefined_confirm_delete_image_title)
        }
        val message = when (action) {
            PredefinedConfirmAction.Merge -> stringResource(
                R.string.predefined_confirm_merge_message,
                sourceLabel,
                targetLabel
            )
            PredefinedConfirmAction.Deduplicate -> stringResource(R.string.predefined_confirm_deduplicate_message)
            PredefinedConfirmAction.DeleteImage -> stringResource(R.string.predefined_confirm_delete_image_message)
        }
        AlertDialog(
            onDismissRequest = { confirmAction = null },
            title = { Text(title) },
            text = { Text(message) },
            confirmButton = {
                TextButton(onClick = {
                    when (action) {
                        PredefinedConfirmAction.Merge -> viewModel.mergeSelected()
                        PredefinedConfirmAction.Deduplicate -> viewModel.deduplicate()
                        PredefinedConfirmAction.DeleteImage -> {
                            pendingDeleteImageId?.let(viewModel::deleteImage)
                            pendingDeleteImageId = null
                        }
                    }
                    confirmAction = null
                }) {
                    Text(stringResource(R.string.common_ok))
                }
            },
            dismissButton = {
                TextButton(onClick = { confirmAction = null }) {
                    Text(stringResource(R.string.predefined_cancel))
                }
            }
        )
    }

    val duplicateCode = state.pendingDuplicateCode
    val duplicateLabel = state.pendingDuplicateExistingLabel
    if (!duplicateCode.isNullOrBlank() && !duplicateLabel.isNullOrBlank()) {
        AlertDialog(
            onDismissRequest = viewModel::dismissDuplicateCodeDialog,
            title = { Text(stringResource(R.string.predefined_duplicate_code_title)) },
            text = {
                Text(
                    stringResource(
                        R.string.predefined_duplicate_code_message,
                        duplicateCode,
                        duplicateLabel
                    )
                )
            },
            confirmButton = {
                TextButton(onClick = viewModel::confirmSaveDuplicateCode) {
                    Text(stringResource(R.string.predefined_save_anyway))
                }
            },
            dismissButton = {
                TextButton(onClick = viewModel::dismissDuplicateCodeDialog) {
                    Text(stringResource(R.string.predefined_cancel))
                }
            }
        )
    }
}

@Composable
private fun ActivityListRow(
    item: PredefinedActivityItem,
    selected: Boolean,
    onClick: () -> Unit
) {
    val minLabel = stringResource(R.string.predefined_min)
    val text = buildString {
        append(item.formatLabel())
        if (!item.duration.isNullOrBlank()) {
            append(" • ")
            append(item.duration)
            append(" ")
            append(minLabel)
        }
        if (!item.durationText.isNullOrBlank()) {
            append(" (")
            append(item.durationText)
            append(")")
        }
    }
    Text(
        text = text,
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
            .padding(vertical = 6.dp),
        style = if (selected) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyMedium
    )
}

private fun PredefinedActivityItem.formatLabel(): String {
    return buildString {
        if (!code.isNullOrBlank()) {
            append("[")
            append(code)
            append("] ")
        }
        append(name)
    }
}
