package com.optix.android.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.horizontalScroll
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.ScrollState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.optix.android.ui.theme.*

@Composable
fun ConsoleStream(
    logs: List<String>,
    modifier: Modifier = Modifier,
    maxLines: Int = 500,
) {
    val listState = rememberLazyListState()
    LaunchedEffect(logs.size) {
        if (logs.isNotEmpty()) listState.animateScrollToItem(logs.lastIndex.coerceAtLeast(0))
    }

    Box(
        modifier = modifier
            .background(T.background.copy(alpha = 0.6f), RoundedCornerShape(8.dp))
            .border(1.dp, T.border.copy(alpha = 0.3f), RoundedCornerShape(8.dp))
            .padding(8.dp),
    ) {
        Box(Modifier.fillMaxSize()) {
            LazyColumn(state = listState, modifier = Modifier.fillMaxSize().padding(end = 6.dp)) {
                val visibleLogs = logs.takeLast(maxLines)
                val startIndex = maxOf(0, logs.size - maxLines)
                
                items(visibleLogs.size) { index ->
                    val line = visibleLogs[index]
                    val lineNumber = (startIndex + index + 1).toString().padStart(3, '0')
                    
                    val (color, icon) = when {
                        line.startsWith("[ERROR]") || line.startsWith("ERR") -> T.warning to "✗"
                        line.startsWith("[+]") || line.startsWith("OK")      -> T.success to "✓"
                        line.startsWith("[*]") || line.startsWith("INFO")    -> T.accentGlow to "●"
                        line.startsWith("[!]") || line.startsWith("WARN")    -> T.warning to "⚡"
                        line.startsWith("[LAN]")                             -> T.accentGlow to "●"
                        line.startsWith("[PORT]")                            -> T.success to "✓"
                        else                                                 -> T.onSurfaceMid to " "
                    }
                    
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .horizontalScroll(rememberScrollState()),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Text(
                            text = lineNumber,
                            color = T.onSurfaceMid.copy(alpha = 0.4f),
                            style = MaterialTheme.typography.bodySmall,
                            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                        )
                        Text(
                            text = icon,
                            color = color,
                            style = MaterialTheme.typography.bodySmall,
                            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                        )
                        androidx.compose.foundation.text.selection.SelectionContainer {
                            Text(
                                text = line,
                                color = color,
                                style = MaterialTheme.typography.bodySmall,
                                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                            )
                        }
                    }
                }
            }
            MinimalLazyScrollbar(
                state = listState,
                itemCount = logs.takeLast(maxLines).size,
                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
            )
        }
    }
}

@Composable
fun MinimalLazyScrollbar(
    state: LazyListState,
    itemCount: Int,
    modifier: Modifier = Modifier,
) {
    if (itemCount <= 0) return
    val layoutInfo = state.layoutInfo
    val visibleItems = layoutInfo.visibleItemsInfo.size.coerceAtLeast(1)
    val thumbRatio = (visibleItems.toFloat() / itemCount).coerceIn(0.12f, 1f)
    val topRatio = (state.firstVisibleItemIndex.toFloat() / itemCount).coerceIn(0f, 1f - thumbRatio)

    BoxWithConstraints(
        modifier = modifier.width(3.dp).background(T.border.copy(alpha = 0.18f), RoundedCornerShape(999.dp))
    ) {
        val travel = maxHeight * (1f - thumbRatio)
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(thumbRatio)
                .offset(y = travel * topRatio)
                .background(T.onSurfaceMid.copy(alpha = 0.55f), RoundedCornerShape(999.dp)),
        )
    }
}

@Composable
fun MinimalScrollScrollbar(
    state: ScrollState,
    modifier: Modifier = Modifier,
) {
    val maxValue = state.maxValue
    if (maxValue <= 0) return

    val thumbRatio = 0.28f
    val topRatio = (state.value.toFloat() / maxValue.toFloat()).coerceIn(0f, 1f - thumbRatio)

    BoxWithConstraints(
        modifier = modifier
            .width(3.dp)
            .background(T.border.copy(alpha = 0.18f), RoundedCornerShape(999.dp)),
    ) {
        val travel = maxHeight * (1f - thumbRatio)
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(thumbRatio)
                .offset(y = travel * topRatio)
                .background(T.onSurfaceMid.copy(alpha = 0.55f), RoundedCornerShape(999.dp)),
        )
    }
}
