package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
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.LogItem
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.LogsViewModel
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

@Composable
fun LogsScreen(
    viewModel: LogsViewModel = viewModel()
) {
    val state by viewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(state.errorMessage) {
        val error = state.errorMessage ?: return@LaunchedEffect
        snackbarHostState.showSnackbar(error.resolve(context))
    }

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.logs_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Text(
                text = stringResource(R.string.logs_title),
                style = MaterialTheme.typography.headlineSmall
            )
            Text(
                text = stringResource(R.string.logs_subtitle),
                style = MaterialTheme.typography.bodyMedium
            )

            state.errorMessage?.let {
                ErrorBanner(
                    message = it.resolve(context),
                    onDismiss = viewModel::clearError
                )
            }

            LogsFiltersSection(
                backend = state.filters.backend,
                logType = state.filters.logType,
                method = state.filters.method,
                statusCode = state.filters.statusCode,
                path = state.filters.path,
                startDate = state.filters.startDate,
                endDate = state.filters.endDate,
                onBackendChanged = viewModel::onBackendChanged,
                onLogTypeChanged = viewModel::onLogTypeChanged,
                onMethodChanged = viewModel::onMethodChanged,
                onStatusCodeChanged = viewModel::onStatusCodeChanged,
                onPathChanged = viewModel::onPathChanged,
                onStartDateChanged = viewModel::onStartDateChanged,
                onEndDateChanged = viewModel::onEndDateChanged,
                onApply = viewModel::applyFilters,
                onClear = viewModel::clearFilters
            )

            if (state.loading) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator()
                }
            } else {
                Text(
                    text = stringResource(
                        R.string.logs_stats,
                        state.total,
                        state.logs.size,
                        state.currentPage,
                        state.totalPages
                    ),
                    style = MaterialTheme.typography.bodyMedium
                )

                if (state.logs.isEmpty()) {
                    Text(text = stringResource(R.string.logs_empty))
                } else {
                    LazyColumn(
                        modifier = Modifier.weight(1f),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(state.logs, key = { it.id }) { log ->
                            LogRow(log = log, onOpen = { viewModel.loadLogDetail(log.id) })
                        }
                    }
                }
            }

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Button(onClick = viewModel::previousPage, enabled = state.canLoadPrevious && !state.loading) {
                    Text(stringResource(R.string.logs_previous))
                }
                Button(onClick = viewModel::nextPage, enabled = state.canLoadNext && !state.loading) {
                    Text(stringResource(R.string.logs_next))
                }
            }

            if (!state.loading && state.logs.isEmpty()) {
                Button(onClick = viewModel::retry, modifier = Modifier.fillMaxWidth()) {
                    Text(stringResource(R.string.common_retry))
                }
            }
        }
    }

    state.selectedLogDetail?.let { detail ->
        AlertDialog(
            onDismissRequest = viewModel::dismissLogDetail,
            title = { Text(text = stringResource(R.string.logs_detail_title, detail.id)) },
            text = {
                Text(
                    text = buildLogDetailText(detail),
                    style = MaterialTheme.typography.bodySmall
                )
            },
            confirmButton = {
                TextButton(onClick = viewModel::dismissLogDetail) {
                    Text(stringResource(R.string.common_ok))
                }
            }
        )
    }
}

@Composable
private fun LogsFiltersSection(
    backend: String,
    logType: String,
    method: String,
    statusCode: String,
    path: String,
    startDate: String,
    endDate: String,
    onBackendChanged: (String) -> Unit,
    onLogTypeChanged: (String) -> Unit,
    onMethodChanged: (String) -> Unit,
    onStatusCodeChanged: (String) -> Unit,
    onPathChanged: (String) -> Unit,
    onStartDateChanged: (String) -> Unit,
    onEndDateChanged: (String) -> Unit,
    onApply: () -> Unit,
    onClear: () -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        OutlinedTextField(
            value = backend,
            onValueChange = onBackendChanged,
            label = { Text(stringResource(R.string.logs_filter_backend)) },
            placeholder = { Text(stringResource(R.string.logs_filter_backend_hint)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        OutlinedTextField(
            value = logType,
            onValueChange = onLogTypeChanged,
            label = { Text(stringResource(R.string.logs_filter_log_type)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        OutlinedTextField(
            value = method,
            onValueChange = onMethodChanged,
            label = { Text(stringResource(R.string.logs_filter_method)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        OutlinedTextField(
            value = statusCode,
            onValueChange = onStatusCodeChanged,
            label = { Text(stringResource(R.string.logs_filter_status)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        OutlinedTextField(
            value = path,
            onValueChange = onPathChanged,
            label = { Text(stringResource(R.string.logs_filter_path)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        OutlinedTextField(
            value = startDate,
            onValueChange = onStartDateChanged,
            label = { Text(stringResource(R.string.logs_filter_start_date)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        OutlinedTextField(
            value = endDate,
            onValueChange = onEndDateChanged,
            label = { Text(stringResource(R.string.logs_filter_end_date)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )

        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = onApply) {
                Text(stringResource(R.string.logs_apply_filters))
            }
            Button(onClick = onClear) {
                Text(stringResource(R.string.logs_clear_filters))
            }
        }
    }
}

@Composable
private fun LogRow(
    log: LogItem,
    onOpen: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onOpen)
            .padding(10.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Text(
            text = "${formatDate(log.createdAt)} | ${log.method} ${log.path}",
            style = MaterialTheme.typography.bodyMedium
        )
        Text(
            text = "${log.logType} | ${log.statusCode ?: "-"} | ${log.executionTime ?: 0}",
            style = MaterialTheme.typography.bodySmall
        )
        log.errorMessage?.takeIf { it.isNotBlank() }?.let {
            Text(text = it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
        }
    }
}

private fun buildLogDetailText(detail: de.trainingstagebuch.app.repository.LogDetailItem): String {
    return buildString {
        appendLine("${detail.method} ${detail.path}")
        appendLine("${detail.logType} | ${detail.statusCode ?: "-"} | ${detail.executionTime ?: 0}")
        if (!detail.ipAddress.isNullOrBlank()) appendLine(detail.ipAddress)
        if (!detail.schedulerJobType.isNullOrBlank()) appendLine(detail.schedulerJobType)
        if (!detail.errorMessage.isNullOrBlank()) {
            appendLine()
            appendLine(detail.errorMessage)
        }
        if (!detail.requestBody.isNullOrBlank()) {
            appendLine()
            appendLine(detail.requestBody)
        }
        if (!detail.responseBody.isNullOrBlank()) {
            appendLine()
            appendLine(detail.responseBody)
        }
    }.trim()
}

private fun formatDate(value: String?): String {
    if (value.isNullOrBlank()) return "-"
    return runCatching {
        OffsetDateTime.parse(value).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"))
    }.getOrElse { value }
}
