package com.example.godeye.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
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.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.godeye.R
import com.example.godeye.models.ConnectionState
import com.example.godeye.models.MainScreenState
import com.example.godeye.ui.components.CameraRequestDialog
import com.example.godeye.ui.components.ConnectionStatusCard
import com.example.godeye.ui.components.SessionsList
import com.example.godeye.ui.viewmodels.MainViewModel
import com.example.godeye.ui.viewmodels.UiEvent
import com.example.godeye.utils.collectAsEffect

/**
 * Главный экран приложения
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    viewModel: MainViewModel = viewModel(),
    onRequestPermissions: () -> Unit,
    onShowError: (String) -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    var serverUrl by remember { mutableStateOf("") }

    // Синхронизируем локальное состояние с ViewModel
    LaunchedEffect(uiState.serverUrl) {
        serverUrl = uiState.serverUrl
    }

    // Обработка UI событий
    LaunchedEffect(viewModel) {
        viewModel.events.collect { event ->
            when (event) {
                is UiEvent.RequestPermissions -> onRequestPermissions()
                is UiEvent.ShowError -> {
                    // Получаем текст ошибки внутри LaunchedEffect
                    val errorMessage = when (event.error) {
                        is com.example.godeye.models.AppError.NetworkError -> "Ошибка сети"
                        is com.example.godeye.models.AppError.CameraPermissionDenied -> "Нет разрешения на камеру"
                        is com.example.godeye.models.AppError.AudioPermissionDenied -> "Нет разрешения на микрофон"
                        is com.example.godeye.models.AppError.CameraNotAvailable -> "Камера недоступна"
                        is com.example.godeye.models.AppError.WebRTCConnectionFailed -> "Ошибка WebRTC соединения"
                        is com.example.godeye.models.AppError.SocketError -> "Ошибка WebSocket: ${event.error.message}"
                        is com.example.godeye.models.AppError.CameraError -> "Ошибка камеры: ${event.error.message}"
                        is com.example.godeye.models.AppError.UnknownError -> "Неизвестная ошибка"
                    }
                    onShowError(errorMessage)
                }
                is UiEvent.ShowMessage -> onShowError(event.message)
                is UiEvent.ShowCameraRequestDialog -> {
                    // Диалог будет показан через состояние showCameraRequest
                }
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = stringResource(R.string.app_name),
                        fontWeight = FontWeight.Bold
                    )
                },
                actions = {
                    IconButton(onClick = { /* TODO: Настройки */ }) {
                        Icon(Icons.Default.Settings, contentDescription = stringResource(R.string.settings))
                    }
                }
            )
        }
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize()) {
            MainContent(
                uiState = uiState,
                serverUrl = serverUrl,
                onServerUrlChange = { serverUrl = it },
                onConnect = {
                    viewModel.updateServerUrl(serverUrl)
                    viewModel.connect()
                },
                onDisconnect = viewModel::disconnect,
                onEndSession = viewModel::endSession,
                modifier = Modifier.padding(paddingValues)
            )

            // Диалог запроса камеры
            uiState.showCameraRequest?.let { request ->
                CameraRequestDialog(
                    request = request,
                    onAccept = { viewModel.respondToCameraRequest(request.sessionId, true) },
                    onDeny = { viewModel.respondToCameraRequest(request.sessionId, false) },
                    onDismiss = { viewModel.respondToCameraRequest(request.sessionId, false) }
                )
            }

            // Индикатор загрузки
            if (uiState.isLoading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Card(
                        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                    ) {
                        Row(
                            modifier = Modifier.padding(16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            CircularProgressIndicator(modifier = Modifier.size(24.dp))
                            Spacer(modifier = Modifier.width(12.dp))
                            Text(stringResource(R.string.loading))
                        }
                    }
                }
            }
        }
    }
}

/**
 * Основное содержимое экрана
 */
@Composable
private fun MainContent(
    uiState: MainScreenState,
    serverUrl: String,
    onServerUrlChange: (String) -> Unit,
    onConnect: () -> Unit,
    onDisconnect: () -> Unit,
    onEndSession: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Информация об устройстве
        DeviceInfoCard(deviceId = uiState.deviceId)

        // Статус подключения
        ConnectionStatusCard(connectionState = uiState.connectionState)

        // Настройки подключения
        ConnectionSettingsCard(
            serverUrl = serverUrl,
            onServerUrlChange = onServerUrlChange,
            connectionState = uiState.connectionState,
            onConnect = onConnect,
            onDisconnect = onDisconnect
        )

        // Список активных сессий
        ActiveSessionsCard(
            sessions = uiState.activeSessions,
            onEndSession = onEndSession
        )
    }
}

/**
 * Карточка с информацией об устройстве
 */
@Composable
private fun DeviceInfoCard(
    deviceId: String,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = stringResource(R.string.device_id_label),
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = deviceId.ifEmpty { "..." },
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

/**
 * Карточка настроек подключения
 */
@Composable
private fun ConnectionSettingsCard(
    serverUrl: String,
    onServerUrlChange: (String) -> Unit,
    connectionState: ConnectionState,
    onConnect: () -> Unit,
    onDisconnect: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Поле ввода URL сервера
            OutlinedTextField(
                value = serverUrl,
                onValueChange = onServerUrlChange,
                label = { Text(stringResource(R.string.server_url_label)) },
                placeholder = { Text(stringResource(R.string.server_url_hint)) },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
                enabled = connectionState == ConnectionState.DISCONNECTED,
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )

            // Кнопка подключения/отключения
            val isConnected = connectionState == ConnectionState.CONNECTED
            val isLoading = connectionState == ConnectionState.CONNECTING ||
                          connectionState == ConnectionState.RECONNECTING

            Button(
                onClick = if (isConnected) onDisconnect else onConnect,
                modifier = Modifier.fillMaxWidth(),
                enabled = !isLoading && serverUrl.isNotBlank()
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                }
                Text(
                    if (isConnected) stringResource(R.string.disconnect_button)
                    else stringResource(R.string.connect_button)
                )
            }
        }
    }
}

/**
 * Карточка активных сессий
 */
@Composable
private fun ActiveSessionsCard(
    sessions: List<com.example.godeye.models.CameraSession>,
    onEndSession: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(R.string.active_sessions_label),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )

                if (sessions.isNotEmpty()) {
                    Badge {
                        Text("${sessions.size}")
                    }
                }
            }

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

            SessionsList(
                sessions = sessions,
                onEndSession = onEndSession
            )
        }
    }
}
