package com.example.godeye.ui.components

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.Person
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.godeye.R
import com.example.godeye.models.CameraSession
import com.example.godeye.utils.Constants
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.*

/**
 * Компонент для отображения списка активных сессий
 */
@Composable
fun SessionsList(
    sessions: List<CameraSession>,
    onEndSession: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    if (sessions.isEmpty()) {
        // Пустое состояние
        Box(
            modifier = modifier.fillMaxWidth(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = stringResource(R.string.no_active_sessions),
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    } else {
        LazyColumn(
            modifier = modifier.fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            contentPadding = PaddingValues(vertical = 8.dp)
        ) {
            items(sessions, key = { it.sessionId }) { session ->
                SessionItem(
                    session = session,
                    onEndSession = { onEndSession(session.sessionId) }
                )
            }
        }
    }
}

/**
 * Элемент списка сессий
 */
@Composable
fun SessionItem(
    session: CameraSession,
    onEndSession: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // Заголовок с оператором
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "${stringResource(R.string.session_operator_label)} ${session.operatorId}",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                }

                // Статус WebRTC
                WebRTCStatusChip(isConnected = session.webRTCConnected)
            }

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

            // Информация о камере
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(
                    imageVector = Icons.Default.Person, // Заменено с Camera на Person
                    contentDescription = null,
                    modifier = Modifier.size(18.dp),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "${stringResource(R.string.session_camera_label)} ${getCameraTypeName(session.cameraType)}",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

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

            // Длительность сессии
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                SessionDuration(startTime = session.startTime)

                // Кнопка завершения сессии
                FilledTonalButton(
                    onClick = onEndSession,
                    colors = ButtonDefaults.filledTonalButtonColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer,
                        contentColor = MaterialTheme.colorScheme.onErrorContainer
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(stringResource(R.string.end_session_button))
                }
            }
        }
    }
}

/**
 * Компонент для отображения статуса WebRTC соединения
 */
@Composable
fun WebRTCStatusChip(
    isConnected: Boolean,
    modifier: Modifier = Modifier
) {
    val backgroundColor = if (isConnected) {
        MaterialTheme.colorScheme.primaryContainer
    } else {
        MaterialTheme.colorScheme.errorContainer
    }

    val contentColor = if (isConnected) {
        MaterialTheme.colorScheme.onPrimaryContainer
    } else {
        MaterialTheme.colorScheme.onErrorContainer
    }

    val statusText = if (isConnected) {
        stringResource(R.string.webrtc_connected)
    } else {
        stringResource(R.string.webrtc_disconnected)
    }

    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(16.dp),
        color = backgroundColor
    ) {
        Text(
            text = stringResource(R.string.session_webrtc_status, statusText),
            style = MaterialTheme.typography.labelSmall,
            color = contentColor,
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
        )
    }
}

/**
 * Компонент для отображения длительности сессии
 */
@Composable
fun SessionDuration(
    startTime: Long,
    modifier: Modifier = Modifier
) {
    var currentTime by remember { mutableStateOf(System.currentTimeMillis()) }

    // Обновляем время каждую секунду
    LaunchedEffect(startTime) {
        while (true) {
            currentTime = System.currentTimeMillis()
            delay(1000)
        }
    }

    val duration = currentTime - startTime
    val hours = (duration / (1000 * 60 * 60)) % 24
    val minutes = (duration / (1000 * 60)) % 60
    val seconds = (duration / 1000) % 60

    Text(
        text = "${stringResource(R.string.session_duration_label)} ${String.format("%02d:%02d:%02d", hours, minutes, seconds)}",
        style = MaterialTheme.typography.bodyMedium,
        color = MaterialTheme.colorScheme.onSurfaceVariant,
        modifier = modifier
    )
}

/**
 * Получить локализованное название типа камеры
 */
@Composable
private fun getCameraTypeName(cameraType: String): String {
    return when (cameraType) {
        Constants.CameraTypes.BACK -> stringResource(R.string.camera_type_back)
        Constants.CameraTypes.FRONT -> stringResource(R.string.camera_type_front)
        Constants.CameraTypes.WIDE -> stringResource(R.string.camera_type_wide)
        Constants.CameraTypes.TELEPHOTO -> stringResource(R.string.camera_type_telephoto)
        else -> cameraType
    }
}
