package com.example.godeye.ui.screens

import androidx.compose.foundation.BorderStroke
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.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.godeye.managers.AutoApprovalManager
import com.example.godeye.managers.ConnectionManager
import com.example.godeye.utils.PreferenceManager
import com.example.godeye.utils.PermissionHelper
import com.example.godeye.ui.components.StreamingVideoView
import com.example.godeye.models.StreamingState
import com.example.godeye.managers.WebRTCManager

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    connectionManager: ConnectionManager,
    autoApprovalManager: AutoApprovalManager,
    preferenceManager: PreferenceManager,
    permissionHelper: PermissionHelper,
    onOpenSettings: () -> Unit
) {
    val connectionState by connectionManager.connectionState.collectAsState(initial = ConnectionManager.ConnectionState.DISCONNECTED)
    val deviceInfo by connectionManager.deviceInfo.collectAsState(initial = null)
    val activeSessions by autoApprovalManager.activeSessions.collectAsState(initial = emptyList())
    val pendingRequest by autoApprovalManager.pendingRequest.collectAsState(initial = null)

    val serverUrl by preferenceManager.serverUrl.collectAsState(initial = "")
    val deviceName by preferenceManager.deviceName.collectAsState(initial = "")
    val autoConnect by preferenceManager.autoConnect.collectAsState(initial = false)
    val autoApprove by preferenceManager.autoApprove.collectAsState(initial = false)

    // НОВОЕ: Состояние трансляции
    val streamingState by connectionManager.webRTCManager.streamingState.collectAsState()
    val isStreamingMode = streamingState.isStreaming

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFF0A1828),
                        Color(0xFF1E3A5F),
                        Color(0xFF2D4A73)
                    )
                )
            )
    ) {
        if (isStreamingMode) {
            // НОВОЕ: Режим трансляции с видео и статистикой
            StreamingModeContent(
                streamingState = streamingState,
                onSwitchCamera = { connectionManager.webRTCManager.switchCamera() },
                onStopStreaming = {
                    streamingState.sessionId?.let { sessionId ->
                        connectionManager.webRTCManager.stopStreaming(sessionId)
                    }
                },
                webRTCManager = connectionManager.webRTCManager // Передаем WebRTCManager
            )
        } else {
            // Обычный режим с плашками настроек
            NormalModeContent(
                connectionState = connectionState,
                deviceInfo = deviceInfo,
                activeSessions = activeSessions,
                pendingRequest = pendingRequest,
                serverUrl = serverUrl,
                deviceName = deviceName,
                autoConnect = autoConnect,
                autoApprove = autoApprove,
                connectionManager = connectionManager,
                autoApprovalManager = autoApprovalManager,
                preferenceManager = preferenceManager,
                permissionHelper = permissionHelper,
                onOpenSettings = onOpenSettings
            )
        }
    }
}

@Composable
private fun StreamingModeContent(
    streamingState: StreamingState,
    onSwitchCamera: () -> Unit,
    onStopStreaming: () -> Unit,
    webRTCManager: com.example.godeye.managers.WebRTCManager // Добавлен параметр webRTCManager
) {
    StreamingVideoView(
        isStreaming = streamingState.isStreaming,
        statistics = streamingState.statistics,
        onStartStreaming = { /* Здесь можно добавить логику запуска трансляции */ },
        onStopStreaming = onStopStreaming,
        webRTCManager = webRTCManager,
        modifier = Modifier.fillMaxSize()
    )
}

@Composable
private fun NormalModeContent(
    connectionState: ConnectionManager.ConnectionState,
    deviceInfo: Any?,
    activeSessions: List<Any>,
    pendingRequest: Any?,
    serverUrl: String,
    deviceName: String,
    autoConnect: Boolean,
    autoApprove: Boolean,
    connectionManager: ConnectionManager,
    autoApprovalManager: AutoApprovalManager,
    preferenceManager: PreferenceManager,
    permissionHelper: PermissionHelper,
    onOpenSettings: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Заголовок с настройками
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = "GodEye",
                    style = MaterialTheme.typography.headlineLarge,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF00BFFF)
                )
                Text(
                    text = "Signal Center",
                    style = MaterialTheme.typography.titleMedium,
                    color = Color(0xFF40E0D0)
                )
            }
            IconButton(
                onClick = onOpenSettings,
                modifier = Modifier
                    .background(
                        Color(0xFF1A2B3D),
                        CircleShape
                    )
            ) {
                Icon(
                    Icons.Default.Settings,
                    contentDescription = "Настройки",
                    tint = Color(0xFF00BFFF)
                )
            }
        }

        // Карточка статуса подключения
        ConnectionStatusCard(
            connectionState = connectionState,
            serverUrl = serverUrl,
            deviceName = deviceName,
            deviceInfo = deviceInfo as? com.example.godeye.models.DeviceInfo,
            onConnect = { connectionManager.connect() },
            onDisconnect = { connectionManager.disconnect() }
        )

        // Карточка настроек
        SettingsOverviewCard(
            autoConnect = autoConnect,
            autoApprove = autoApprove,
            hasAllPermissions = permissionHelper.hasAllPermissions(),
            onOpenSettings = onOpenSettings
        )

        // Тестовая кнопка для проверки автоподтверждения
        if (connectionState == ConnectionManager.ConnectionState.CONNECTED) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFF2D4A22).copy(alpha = 0.8f)
                ),
                border = BorderStroke(1.dp, Color(0xFF4CAF50))
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Column {
                        Text(
                            text = "Тестирование автоподтверждения",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold,
                            color = Color(0xFF4CAF50)
                        )
                        Text(
                            text = "Имитирует запрос камеры от оператора",
                            style = MaterialTheme.typography.bodyMedium,
                            color = Color(0xFFB3B3B3)
                        )
                    }

                    Button(
                        onClick = { connectionManager.testAutoApproval() },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF4CAF50)
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.PlayArrow,
                            contentDescription = "Тест"
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("Тест")
                    }
                }
            }
        }

        // Pending запрос (если есть)
        pendingRequest?.let { request ->
            if (request is org.json.JSONObject) {
                PendingRequestCard(
                    request = request,
                    onApprove = { sessionId, operatorId, cameraType ->
                        autoApprovalManager.approveRequest(sessionId, operatorId, cameraType)
                    },
                    onDeny = { sessionId ->
                        autoApprovalManager.denyRequest(sessionId)
                    }
                )
            }
        }

        // Активные сессии
        if (activeSessions.isNotEmpty()) {
            Text(
                text = "Активные сессии (${activeSessions.size})",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.SemiBold,
                color = Color(0xFF00BFFF)
            )

            LazyColumn(
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(activeSessions) { session ->
                    if (session is AutoApprovalManager.CameraSession) {
                        ActiveSessionCard(session = session)
                    }
                }
            }
        } else {
            // Пустое состояние
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFF1A2B3D).copy(alpha = 0.8f)
                ),
                border = BorderStroke(1.dp, Color(0xFF40E0D0).copy(alpha = 0.3f))
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Icon(
                        Icons.Default.Add,
                        contentDescription = null,
                        modifier = Modifier.size(48.dp),
                        tint = Color(0xFF40E0D0)
                    )
                    Text(
                        text = "Нет активных сессий",
                        style = MaterialTheme.typography.titleMedium,
                        color = Color(0xFFE0F4FF)
                    )
                    Text(
                        text = "Ожидание запросов от операторов",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color(0xFFB0C4DE)
                    )
                }
            }
        }
    }
}

@Composable
private fun ConnectionStatusCard(
    connectionState: ConnectionManager.ConnectionState,
    serverUrl: String,
    deviceName: String,
    deviceInfo: com.example.godeye.models.DeviceInfo?,
    onConnect: () -> Unit,
    onDisconnect: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = when (connectionState) {
                ConnectionManager.ConnectionState.CONNECTED -> MaterialTheme.colorScheme.primaryContainer
                ConnectionManager.ConnectionState.CONNECTING -> MaterialTheme.colorScheme.tertiaryContainer
                ConnectionManager.ConnectionState.ERROR -> MaterialTheme.colorScheme.errorContainer
                ConnectionManager.ConnectionState.DISCONNECTED -> MaterialTheme.colorScheme.surfaceVariant
                ConnectionManager.ConnectionState.RECONNECTING -> MaterialTheme.colorScheme.tertiaryContainer
            }
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Подключение к серверу",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Medium
                )

                when (connectionState) {
                    ConnectionManager.ConnectionState.CONNECTED -> {
                        Button(
                            onClick = onDisconnect,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.error
                            )
                        ) {
                            Text("Отключиться")
                        }
                    }
                    ConnectionManager.ConnectionState.CONNECTING -> {
                        CircularProgressIndicator(modifier = Modifier.size(24.dp))
                    }
                    else -> {
                        Button(onClick = onConnect) {
                            Text("Подключиться")
                        }
                    }
                }
            }

            // Статус
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    when (connectionState) {
                        ConnectionManager.ConnectionState.CONNECTED -> Icons.Default.CheckCircle
                        ConnectionManager.ConnectionState.CONNECTING -> Icons.Default.Refresh
                        ConnectionManager.ConnectionState.ERROR -> Icons.Default.Warning
                        ConnectionManager.ConnectionState.DISCONNECTED -> Icons.Default.Close
                        ConnectionManager.ConnectionState.RECONNECTING -> Icons.Default.Refresh
                    },
                    contentDescription = null,
                    tint = when (connectionState) {
                        ConnectionManager.ConnectionState.CONNECTED -> MaterialTheme.colorScheme.onPrimaryContainer
                        ConnectionManager.ConnectionState.CONNECTING -> MaterialTheme.colorScheme.onTertiaryContainer
                        ConnectionManager.ConnectionState.ERROR -> MaterialTheme.colorScheme.onErrorContainer
                        ConnectionManager.ConnectionState.DISCONNECTED -> MaterialTheme.colorScheme.onSurfaceVariant
                        ConnectionManager.ConnectionState.RECONNECTING -> MaterialTheme.colorScheme.onTertiaryContainer
                    }
                )
                Text(
                    text = when (connectionState) {
                        ConnectionManager.ConnectionState.CONNECTED -> "Подключено"
                        ConnectionManager.ConnectionState.CONNECTING -> "Подключение..."
                        ConnectionManager.ConnectionState.ERROR -> "Ошибка соединения"
                        ConnectionManager.ConnectionState.DISCONNECTED -> "Отключено"
                        ConnectionManager.ConnectionState.RECONNECTING -> "Переподключение..."
                    },
                    style = MaterialTheme.typography.bodyMedium
                )
            }

            // Информация о сервере
            Text(
                text = "Сервер: $serverUrl",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

            Text(
                text = "Устройство: $deviceName",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

            if (deviceInfo is com.example.godeye.models.DeviceInfo) {
                Text(
                    text = "Модель: ${deviceInfo.manufacturer} ${deviceInfo.model} (Android ${deviceInfo.androidVersion})",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
private fun SettingsOverviewCard(
    autoConnect: Boolean,
    autoApprove: Boolean,
    hasAllPermissions: Boolean,
    onOpenSettings: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Быстрые настройки",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Medium
                )
                TextButton(onClick = onOpenSettings) {
                    Text("Все настройки")
                    Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null)
                }
            }

            // Статусы настроек
            SettingStatusRow("Автоподключение", autoConnect)
            SettingStatusRow("Автоподтверждение", autoApprove, isWarning = autoApprove)
            SettingStatusRow("Разрешения", hasAllPermissions, isError = !hasAllPermissions)
        }
    }
}

@Composable
private fun SettingStatusRow(
    title: String,
    enabled: Boolean,
    isWarning: Boolean = false,
    isError: Boolean = false
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            if (enabled) Icons.Default.Check else Icons.Default.Close,
            contentDescription = null,
            tint = when {
                isError -> MaterialTheme.colorScheme.error
                isWarning -> MaterialTheme.colorScheme.tertiary
                enabled -> MaterialTheme.colorScheme.primary
                else -> MaterialTheme.colorScheme.onSurfaceVariant
            }
        )
        Text(
            text = title,
            style = MaterialTheme.typography.bodyMedium,
            color = when {
                isError -> MaterialTheme.colorScheme.error
                isWarning -> MaterialTheme.colorScheme.tertiary
                else -> MaterialTheme.colorScheme.onSurfaceVariant
            }
        )
    }
}

@Composable
private fun PendingRequestCard(
    request: org.json.JSONObject,
    onApprove: (String, String, String) -> Unit,
    onDeny: (String) -> Unit
) {
    val sessionId = request.optString("sessionId")
    val operatorId = request.optString("operatorId")
    val cameraType = request.optString("cameraType", "back")

    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2D4A22).copy(alpha = 0.8f)
        ),
        border = BorderStroke(1.dp, Color(0xFFFF9800))
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    Icons.Default.NotificationImportant,
                    contentDescription = null,
                    tint = Color(0xFFFF9800),
                    modifier = Modifier.size(24.dp)
                )
                Text(
                    text = "Входящий запрос камеры",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFFFF9800)
                )
            }

            HorizontalDivider(
                color = Color(0xFFFF9800).copy(alpha = 0.3f),
                thickness = 1.dp
            )

            // UUID оператора
            Column(
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = "UUID оператора:",
                    style = MaterialTheme.typography.bodySmall,
                    color = Color(0xFFB0C4DE)
                )
                Text(
                    text = operatorId,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFFE0F4FF),
                    modifier = Modifier
                        .background(
                            Color(0xFF2D4A73).copy(alpha = 0.5f),
                            shape = MaterialTheme.shapes.small
                        )
                        .padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }

            // Информация о запросе
            Column(
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Column {
                        Text(
                            text = "Запрашиваемая камера:",
                            style = MaterialTheme.typography.bodySmall,
                            color = Color(0xFFB0C4DE)
                        )
                        Text(
                            text = getCameraDisplayName(cameraType),
                            style = MaterialTheme.typography.bodyMedium,
                            color = Color(0xFFE0F4FF)
                        )
                    }

                    Column(
                        horizontalAlignment = Alignment.End
                    ) {
                        Text(
                            text = "ID сессии:",
                            style = MaterialTheme.typography.bodySmall,
                            color = Color(0xFFB0C4DE)
                        )
                        Text(
                            text = sessionId.take(8) + "...",
                            style = MaterialTheme.typography.bodySmall,
                            color = Color(0xFFE0F4FF)
                        )
                    }
                }
            }

            // Предупреждение
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFFFF9800).copy(alpha = 0.1f)
                ),
                border = BorderStroke(1.dp, Color(0xFFFF9800).copy(alpha = 0.3f))
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.Warning,
                        contentDescription = null,
                        tint = Color(0xFFFF9800),
                        modifier = Modifier.size(16.dp)
                    )
                    Text(
                        text = "Убедитесь, что вы доверяете этому оператору",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFFFF9800)
                    )
                }
            }

            // Кнопки действий
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                OutlinedButton(
                    onClick = { onDeny(sessionId) },
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.outlinedButtonColors(
                        contentColor = Color(0xFFF44336)
                    ),
                    border = BorderStroke(1.dp, Color(0xFFF44336))
                ) {
                    Icon(
                        Icons.Default.Close,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Отклонить")
                }

                Button(
                    onClick = { onApprove(sessionId, operatorId, cameraType) },
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF4CAF50)
                    )
                ) {
                    Icon(
                        Icons.Default.Check,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Разрешить")
                }
            }
        }
    }
}

@Composable
private fun ActiveSessionCard(
    session: AutoApprovalManager.CameraSession
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A2B3D).copy(alpha = 0.9f)
        ),
        border = BorderStroke(1.dp, Color(0xFF00BFFF).copy(alpha = 0.5f))
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // Заголовок с состоянием
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Подключенный оператор",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF00BFFF)
                )

                // Индикатор состояния
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(8.dp)
                            .background(
                                color = when (session.streamingState) {
                                    AutoApprovalManager.StreamingState.STREAMING -> Color(0xFF4CAF50)
                                    AutoApprovalManager.StreamingState.CONNECTING -> Color(0xFFFF9800)
                                    AutoApprovalManager.StreamingState.ERROR -> Color(0xFFF44336)
                                    else -> Color(0xFF9E9E9E)
                                },
                                shape = CircleShape
                            )
                    )
                    Text(
                        text = when (session.streamingState) {
                            AutoApprovalManager.StreamingState.STREAMING -> "Активна"
                            AutoApprovalManager.StreamingState.CONNECTING -> "Подключение"
                            AutoApprovalManager.StreamingState.ERROR -> "Ошибка"
                            else -> "Ожидание"
                        },
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFFB0C4DE)
                    )
                }
            }

            HorizontalDivider(
                color = Color(0xFF40E0D0).copy(alpha = 0.3f),
                thickness = 1.dp
            )

            // UUID оператора
            Column(
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = "UUID оператора:",
                    style = MaterialTheme.typography.bodySmall,
                    color = Color(0xFFB0C4DE)
                )
                Text(
                    text = session.operatorId,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFFE0F4FF),
                    // Делаем текст выделяемым для копирования
                    modifier = Modifier
                        .background(
                            Color(0xFF2D4A73).copy(alpha = 0.5f),
                            shape = MaterialTheme.shapes.small
                        )
                        .padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }

            // Информация о камере и времени
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Column(
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Text(
                        text = "Камера:",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFFB0C4DE)
                    )
                    Text(
                        text = getCameraDisplayName(session.cameraType),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFFE0F4FF)
                    )
                }

                Column(
                    verticalArrangement = Arrangement.spacedBy(2.dp),
                    horizontalAlignment = Alignment.End
                ) {
                    Text(
                        text = "Длительность:",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFFB0C4DE)
                    )
                    Text(
                        text = formatDuration(System.currentTimeMillis() - session.startTime),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFFE0F4FF)
                    )
                }
            }

            // Дополнительная информация
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = if (session.isAutoApproved) "Автоматически одобрено" else "Одобрено вручную",
                    style = MaterialTheme.typography.bodySmall,
                    color = if (session.isAutoApproved) Color(0xFF4CAF50) else Color(0xFF2196F3)
                )

                Icon(
                    imageVector = Icons.Default.Videocam,
                    contentDescription = "Камера активна",
                    tint = Color(0xFF00BFFF),
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}

// Вспомогательная функция для форматирования времени
private fun formatDuration(durationMs: Long): String {
    val seconds = (durationMs / 1000) % 60
    val minutes = (durationMs / (1000 * 60)) % 60
    val hours = (durationMs / (1000 * 60 * 60)) % 24

    return when {
        hours > 0 -> String.format("%02d:%02d:%02d", hours, minutes, seconds)
        else -> String.format("%02d:%02d", minutes, seconds)
    }
}

// Вспомогательная функция для отображения типа камеры
private fun getCameraDisplayName(cameraType: String): String {
    return when (cameraType) {
        "back" -> "Основная камера"
        "front" -> "Фронтальная камера"
        "wide" -> "Широкоугольная камера"
        "telephoto" -> "Телеобъектив"
        else -> "Камера"
    }
}
