package com.example.godeye.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.godeye.utils.Logger

/**
 * Компонент для отображения детальной информации о WebRTC соединениях
 */
@Composable
fun NetworkTrafficMonitor(
    sessionId: String?,
    modifier: Modifier = Modifier
) {
    // Состояние для отслеживания логов
    var networkLogs by remember { mutableStateOf(listOf<NetworkLogEntry>()) }
    var isExpanded by remember { mutableStateOf(false) }

    // Подписываемся на логи (в реальном приложении это бы было через Flow)
    LaunchedEffect(sessionId) {
        // Здесь мы бы подписались на логи, но для демонстрации создадим тестовые данные
        networkLogs = listOf(
            NetworkLogEntry("WEBRTC_ICE_SERVERS", "ICE servers: stun:stun.l.google.com:19302", System.currentTimeMillis()),
            NetworkLogEntry("WEBRTC_SDP_CANDIDATE", "UDP candidate: 192.168.1.100:54321", System.currentTimeMillis()),
            NetworkLogEntry("WEBRTC_CONNECTION_STATE", "ICE connection state: CONNECTED", System.currentTimeMillis()),
            NetworkLogEntry("WEBRTC_VIDEO_STATS", "Sending video to remote peer", System.currentTimeMillis())
        )
    }

    Card(
        modifier = modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A2B3D).copy(alpha = 0.9f)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // Заголовок с кнопкой раскрытия
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.NetworkCheck,
                        contentDescription = null,
                        tint = Color(0xFF00BFFF),
                        modifier = Modifier.size(24.dp)
                    )
                    Text(
                        text = "📡 Мониторинг трафика",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF00BFFF)
                    )
                }

                IconButton(
                    onClick = { isExpanded = !isExpanded }
                ) {
                    Icon(
                        imageVector = if (isExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
                        contentDescription = if (isExpanded) "Скрыть" else "Показать",
                        tint = Color(0xFF00BFFF)
                    )
                }
            }

            if (isExpanded) {
                Spacer(modifier = Modifier.height(12.dp))

                // Информация о текущем соединении
                if (sessionId != null) {
                    ConnectionSummary(sessionId = sessionId)
                    Spacer(modifier = Modifier.height(12.dp))
                }

                // Логи сетевой активности
                Text(
                    text = "Сетевые логи:",
                    fontSize = 14.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFFE0F4FF)
                )

                Spacer(modifier = Modifier.height(8.dp))

                LazyColumn(
                    modifier = Modifier.heightIn(max = 200.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    items(networkLogs.reversed()) { log ->
                        NetworkLogItem(log = log)
                    }
                }
            } else {
                // Краткая информация когда свернуто
                Spacer(modifier = Modifier.height(8.dp))
                if (sessionId != null) {
                    Text(
                        text = "Активная сессия: $sessionId",
                        fontSize = 14.sp,
                        color = Color(0xFF40E0D0)
                    )
                    Text(
                        text = "Статус: Передача видео активна",
                        fontSize = 12.sp,
                        color = Color(0xFFB0C4DE)
                    )
                } else {
                    Text(
                        text = "Нет активных соединений",
                        fontSize = 14.sp,
                        color = Color(0xFFB0C4DE)
                    )
                }
            }
        }
    }
}

@Composable
private fun ConnectionSummary(sessionId: String) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2D4A73).copy(alpha = 0.7f)
        )
    ) {
        Column(
            modifier = Modifier.padding(12.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "Сессия:",
                    fontSize = 12.sp,
                    color = Color(0xFFB0C4DE)
                )
                Text(
                    text = sessionId,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFFE0F4FF)
                )
            }

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "Протокол:",
                    fontSize = 12.sp,
                    color = Color(0xFFB0C4DE)
                )
                Text(
                    text = "WebRTC (UDP/STUN)",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFFE0F4FF)
                )
            }

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "Назначение:",
                    fontSize = 12.sp,
                    color = Color(0xFFB0C4DE)
                )
                Text(
                    text = "Удаленный оператор",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF40E0D0)
                )
            }
        }
    }
}

@Composable
private fun NetworkLogItem(log: NetworkLogEntry) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                Color(0xFF0A1828).copy(alpha = 0.5f),
                RoundedCornerShape(4.dp)
            )
            .padding(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // Индикатор типа лога
        val (icon, color) = when {
            log.type.contains("CANDIDATE") -> Icons.Default.LocationOn to Color(0xFF4CAF50)
            log.type.contains("CONNECTION") -> Icons.Default.Link to Color(0xFF2196F3)
            log.type.contains("STATS") -> Icons.Default.Analytics to Color(0xFFFF9800)
            log.type.contains("SDP") -> Icons.Default.Code to Color(0xFF9C27B0)
            else -> Icons.Default.Info to Color(0xFF607D8B)
        }

        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = color,
            modifier = Modifier.size(16.dp)
        )

        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = log.type,
                fontSize = 10.sp,
                fontWeight = FontWeight.Bold,
                color = color
            )
            Text(
                text = log.message,
                fontSize = 11.sp,
                color = Color(0xFFE0F4FF),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
        }

        // Временная метка
        Text(
            text = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date(log.timestamp)),
            fontSize = 10.sp,
            color = Color(0xFFB0C4DE)
        )
    }
}

data class NetworkLogEntry(
    val type: String,
    val message: String,
    val timestamp: Long
)
