package com.fmdxconnector

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.border
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.platform.LocalClipboardManager
import kotlinx.coroutines.launch

@Composable
fun LoggingPanel(
    modifier: Modifier = Modifier,
    title: String = "System Logs"
) {
    val logs by LogCenter.logs.collectAsStateWithLifecycle()
    val clipboardManager = LocalClipboardManager.current
    val shape = RoundedCornerShape(8.dp)
    val border = androidx.compose.foundation.BorderStroke(1.dp, MaterialTheme.colorScheme.outline)
    val listState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()

    // Auto-scroll to the bottom when a new log is added
    LaunchedEffect(logs.size) {
        if (logs.isNotEmpty()) {
            coroutineScope.launch {
                listState.animateScrollToItem(logs.size - 1)
            }
        }
    }

    Column(modifier = modifier) {
        // Titel und Button-Reihe (jetzt außerhalb der Box)
        Row(
            Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.labelLarge,
                color = Color.White, // Geändert zu Weiß
                modifier = Modifier.weight(1f)
            )
            Button(
                onClick = {
                    val logString = logs.joinToString(separator = "\n") {
                        "${it.timestamp} [${it.level}] ${it.message}"
                    }
                    clipboardManager.setText(AnnotatedString(logString))
                },
                modifier = Modifier
                    .height(40.dp)
                    .widthIn(min = 100.dp),
                shape = RoundedCornerShape(8.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF64B5F6),
                    contentColor = Color.White
                ),
                contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp)
            ) {
                Text(
                    "Copy Logs",
                    fontWeight = FontWeight.Bold,
                    fontSize = MaterialTheme.typography.labelMedium.fontSize
                )
            }
        }
        Spacer(Modifier.height(8.dp))

        // Die eigentliche Log-Box
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.surface, shape)
                .border(border, shape)
                .padding(12.dp)
        ) {
            items(logs) { entry -> // Nicht mehr umgekehrt
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(vertical = 2.dp)
                ) {
                    // Zeitstempel
                    Text(
                        text = entry.timestamp,
                        style = MaterialTheme.typography.labelSmall,
                        color = Color.Gray,
                        fontSize = 10.sp,
                        maxLines = 1,
                        modifier = Modifier.width(55.dp)
                    )
                    Spacer(Modifier.width(6.dp))

                    // Level-Badge
                    val levelColor = when (entry.level) {
                        LogLevel.ERROR -> Color(0xFFD32F2F)
                        LogLevel.WARNING -> Color(0xFFFFA000)
                        LogLevel.SUCCESS -> Color(0xFF388E3C)
                        LogLevel.INFO -> MaterialTheme.colorScheme.primary
                    }
                    Box(
                        modifier = Modifier
                            .width(65.dp)
                            .background(levelColor.copy(alpha = 0.15f), RoundedCornerShape(6.dp))
                            .padding(horizontal = 6.dp, vertical = 2.dp)
                    ) {
                        Text(
                            text = entry.level.name,
                            color = levelColor,
                            fontSize = 10.sp,
                            maxLines = 1
                        )
                    }
                    Spacer(Modifier.width(10.dp))

                    // Nachricht
                    Text(
                        text = entry.message,
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }
            }
        }
    }
}

@Composable
fun LogRow(log: LogEntry) {
    val levelColor = when (log.level) {
        LogLevel.ERROR   -> Color(0xFFFF5252)
        LogLevel.WARNING -> Color(0xFFFFD700)
        LogLevel.SUCCESS -> Color(0xFF90BF00)
        LogLevel.INFO    -> Color(0xFF64B5F6)
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = log.timestamp,
            style = MaterialTheme.typography.labelSmall,
            color = Color.Gray,
            fontSize = 10.sp,
            maxLines = 1,
            softWrap = false,
            modifier = Modifier.width(60.dp)
        )
        Spacer(Modifier.width(6.dp))
        Box(
            modifier = Modifier
                .width(75.dp)
                .background(levelColor.copy(alpha = 0.15f), RoundedCornerShape(6.dp))
                .padding(horizontal = 6.dp, vertical = 2.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = log.level.name,
                color = levelColor,
                fontSize = 10.sp,
                maxLines = 1,
                softWrap = false,
                textAlign = TextAlign.Center
            )
        }
        Spacer(Modifier.width(10.dp))
        Text(
            text = log.message,
            style = MaterialTheme.typography.labelSmall,
            color = Color.White,
            fontSize = 9.sp
        )
    }
}

private fun Modifier.simpleVerticalScrollbar(state: LazyListState): Modifier =
    this.then(
        Modifier.drawWithContent {
            drawContent()

            val info = state.layoutInfo
            val total = info.totalItemsCount
            val visible = info.visibleItemsInfo.size
            if (total == 0 || visible == 0) return@drawWithContent

            val first = state.firstVisibleItemIndex
            val canvasSize: Size = this.size
            val contentHeight = canvasSize.height

            val thumbHeight = (visible.toFloat() / total.toFloat() * contentHeight).coerceAtLeast(16f)
            val denom = (total - visible).coerceAtLeast(1)
            val progress = first.toFloat() / denom.toFloat()
            val top = (contentHeight - thumbHeight) * progress

            drawRoundRect(
                color = Color(0x50FFFFFF),
                topLeft = Offset(x = canvasSize.width - 4.dp.toPx(), y = top),
                size = Size(width = 2.dp.toPx(), height = thumbHeight),
                cornerRadius = CornerRadius(1.dp.toPx(), 1.dp.toPx())
            )
        }
    )