package com.example.godeye.ui.components

import androidx.compose.animation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
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.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.content.edit
import com.example.godeye.ui.theme.GodEyeColors
import com.example.godeye.utils.getPreferences

/**
 * Экран настроек GodEye с расширенными параметрами
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onBackPressed: () -> Unit,
    onServerConfigSaved: (String) -> Unit
) {
    val context = LocalContext.current
    val prefs = context.getPreferences()

    // Состояния настроек
    var serverUrl by remember {
        mutableStateOf(prefs.getString("server_url", "http://192.168.219.108:3001") ?: "")
    }
    var deviceName by remember {
        mutableStateOf(prefs.getString("device_name", "${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}") ?: "")
    }
    var autoConnect by remember {
        mutableStateOf(prefs.getBoolean("auto_connect", false))
    }
    var autoAcceptRequests by remember {
        mutableStateOf(prefs.getBoolean("auto_accept_requests", true))
    }
    var enableNotifications by remember {
        mutableStateOf(prefs.getBoolean("enable_notifications", true))
    }
    var keepScreenOn by remember {
        mutableStateOf(prefs.getBoolean("keep_screen_on", false))
    }
    var preferredCamera by remember {
        mutableStateOf(prefs.getString("preferred_camera", "back") ?: "back")
    }
    var streamQuality by remember {
        mutableStateOf(prefs.getString("stream_quality", "720p") ?: "720p")
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .systemBarsPadding()
    ) {
        // Шапка экрана
        TopAppBar(
            title = {
                Text(
                    text = "Настройки GodEye",
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Medium,
                    color = GodEyeColors.IvoryPure
                )
            },
            navigationIcon = {
                IconButton(onClick = onBackPressed) {
                    Icon(
                        Icons.Default.ArrowBack,
                        contentDescription = "Назад",
                        tint = GodEyeColors.IvoryPure
                    )
                }
            },
            actions = {
                TextButton(
                    onClick = {
                        // Сохраняем все настройки
                        prefs.edit {
                            putString("server_url", serverUrl)
                            putString("device_name", deviceName)
                            putBoolean("auto_connect", autoConnect)
                            putBoolean("auto_accept_requests", autoAcceptRequests)
                            putBoolean("enable_notifications", enableNotifications)
                            putBoolean("keep_screen_on", keepScreenOn)
                            putString("preferred_camera", preferredCamera)
                            putString("stream_quality", streamQuality)
                        }
                        onServerConfigSaved(serverUrl)
                    }
                ) {
                    Text(
                        "Сохранить",
                        color = GodEyeColors.SuccessGreen,
                        fontWeight = FontWeight.Medium
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = GodEyeColors.BlackSoft.copy(alpha = 0.9f)
            )
        )

        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Секция "Сервер"
            item {
                SettingsSection(title = "Подключение к серверу") {
                    OutlinedTextField(
                        value = serverUrl,
                        onValueChange = { serverUrl = it },
                        label = { Text("URL сервера") },
                        placeholder = { Text("http://192.168.1.100:3001") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = GodEyeColors.NavyLight,
                            unfocusedBorderColor = GodEyeColors.IvorySoft.copy(alpha = 0.5f),
                            focusedTextColor = GodEyeColors.IvoryPure,
                            unfocusedTextColor = GodEyeColors.IvorySoft,
                            focusedLabelColor = GodEyeColors.NavyLight,
                            unfocusedLabelColor = GodEyeColors.IvorySoft
                        ),
                        leadingIcon = {
                            Icon(
                                Icons.Default.Language,
                                contentDescription = null,
                                tint = GodEyeColors.NavyLight
                            )
                        }
                    )

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

                    SettingsSwitchCard(
                        title = "Автоматическое подключение",
                        subtitle = "Подключаться к серверу при запуске приложения",
                        checked = autoConnect,
                        onCheckedChange = { autoConnect = it },
                        icon = Icons.Default.AutoAwesome
                    )
                }
            }

            // Секция "Устройство"
            item {
                SettingsSection(title = "Устройство") {
                    OutlinedTextField(
                        value = deviceName,
                        onValueChange = { deviceName = it },
                        label = { Text("Имя устройства") },
                        placeholder = { Text("Android Device") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = GodEyeColors.NavyLight,
                            unfocusedBorderColor = GodEyeColors.IvorySoft.copy(alpha = 0.5f),
                            focusedTextColor = GodEyeColors.IvoryPure,
                            unfocusedTextColor = GodEyeColors.IvorySoft,
                            focusedLabelColor = GodEyeColors.NavyLight,
                            unfocusedLabelColor = GodEyeColors.IvorySoft
                        ),
                        leadingIcon = {
                            Icon(
                                Icons.Default.Smartphone,
                                contentDescription = null,
                                tint = GodEyeColors.NavyLight
                            )
                        }
                    )

                    Text(
                        text = "Это имя будет отображаться операторам при подключении",
                        style = MaterialTheme.typography.bodySmall,
                        color = GodEyeColors.IvorySoft,
                        modifier = Modifier.padding(start = 48.dp, top = 4.dp)
                    )
                }
            }

            // Секция "Автоматизация"
            item {
                SettingsSection(title = "Автоматизация") {
                    SettingsSwitchCard(
                        title = "Автоматическое принятие запросов",
                        subtitle = "Автоматически принимать запросы от операторов",
                        checked = autoAcceptRequests,
                        onCheckedChange = { autoAcceptRequests = it },
                        icon = Icons.Default.AutoAwesome
                    )

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

                    SettingsSwitchCard(
                        title = "Уведомления",
                        subtitle = "Показывать уведомления о входящих запросах",
                        checked = enableNotifications,
                        onCheckedChange = { enableNotifications = it },
                        icon = Icons.Default.Notifications
                    )

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

                    SettingsSwitchCard(
                        title = "Не выключать экран",
                        subtitle = "Экран остается включенным во время сессии",
                        checked = keepScreenOn,
                        onCheckedChange = { keepScreenOn = it },
                        icon = Icons.Default.ScreenLockPortrait
                    )
                }
            }

            // Секция "Камера"
            item {
                SettingsSection(title = "Камера") {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = GodEyeColors.NavyDark.copy(alpha = 0.3f)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(12.dp)
                            ) {
                                Icon(
                                    Icons.Default.CameraAlt,
                                    contentDescription = null,
                                    tint = GodEyeColors.NavyLight,
                                    modifier = Modifier.size(24.dp)
                                )
                                Column(
                                    modifier = Modifier.weight(1f)
                                ) {
                                    Text(
                                        text = "Предпочитаемая камера",
                                        style = MaterialTheme.typography.titleSmall,
                                        fontWeight = FontWeight.Medium,
                                        color = GodEyeColors.IvoryPure
                                    )
                                    Text(
                                        text = "Камера по умолчанию для стриминга",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = GodEyeColors.IvorySoft
                                    )
                                }
                            }

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

                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                FilterChip(
                                    onClick = { preferredCamera = "back" },
                                    label = { Text("Основная") },
                                    selected = preferredCamera == "back",
                                    colors = FilterChipDefaults.filterChipColors(
                                        selectedContainerColor = GodEyeColors.NavyLight,
                                        selectedLabelColor = GodEyeColors.IvoryPure
                                    )
                                )
                                FilterChip(
                                    onClick = { preferredCamera = "front" },
                                    label = { Text("Фронтальная") },
                                    selected = preferredCamera == "front",
                                    colors = FilterChipDefaults.filterChipColors(
                                        selectedContainerColor = GodEyeColors.NavyLight,
                                        selectedLabelColor = GodEyeColors.IvoryPure
                                    )
                                )
                            }
                        }
                    }

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

                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = GodEyeColors.NavyDark.copy(alpha = 0.3f)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(12.dp)
                            ) {
                                Icon(
                                    Icons.Default.HighQuality,
                                    contentDescription = null,
                                    tint = GodEyeColors.NavyLight,
                                    modifier = Modifier.size(24.dp)
                                )
                                Column(
                                    modifier = Modifier.weight(1f)
                                ) {
                                    Text(
                                        text = "Качество видео",
                                        style = MaterialTheme.typography.titleSmall,
                                        fontWeight = FontWeight.Medium,
                                        color = GodEyeColors.IvoryPure
                                    )
                                    Text(
                                        text = "Разрешение видео потока",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = GodEyeColors.IvorySoft
                                    )
                                }
                            }

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

                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                FilterChip(
                                    onClick = { streamQuality = "480p" },
                                    label = { Text("480p") },
                                    selected = streamQuality == "480p",
                                    colors = FilterChipDefaults.filterChipColors(
                                        selectedContainerColor = GodEyeColors.NavyLight,
                                        selectedLabelColor = GodEyeColors.IvoryPure
                                    )
                                )
                                FilterChip(
                                    onClick = { streamQuality = "720p" },
                                    label = { Text("720p") },
                                    selected = streamQuality == "720p",
                                    colors = FilterChipDefaults.filterChipColors(
                                        selectedContainerColor = GodEyeColors.NavyLight,
                                        selectedLabelColor = GodEyeColors.IvoryPure
                                    )
                                )
                                FilterChip(
                                    onClick = { streamQuality = "1080p" },
                                    label = { Text("1080p") },
                                    selected = streamQuality == "1080p",
                                    colors = FilterChipDefaults.filterChipColors(
                                        selectedContainerColor = GodEyeColors.NavyLight,
                                        selectedLabelColor = GodEyeColors.IvoryPure
                                    )
                                )
                            }
                        }
                    }
                }
            }

            // Секция "О приложении"
            item {
                SettingsSection(title = "О приложении") {
                    InfoCard(
                        title = "GodEye Android Client",
                        subtitle = "Версия 1.0.0 (Build 1)",
                        icon = Icons.Default.Info
                    )

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

                    InfoCard(
                        title = "Device ID",
                        subtitle = context.getPreferences().getString("device_id", "Неизвестно") ?: "Неизвестно",
                        icon = Icons.Default.Fingerprint
                    )
                }
            }
        }
    }
}

@Composable
private fun SettingsSection(
    title: String,
    content: @Composable ColumnScope.() -> Unit
) {
    Column {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold,
            color = GodEyeColors.IvoryPure,
            modifier = Modifier.padding(bottom = 12.dp)
        )
        content()
    }
}

@Composable
private fun SettingsSwitchCard(
    title: String,
    subtitle: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    icon: androidx.compose.ui.graphics.vector.ImageVector
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = GodEyeColors.NavyDark.copy(alpha = 0.3f)
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = if (checked) GodEyeColors.SuccessGreen else GodEyeColors.IvorySoft,
                modifier = Modifier.size(24.dp)
            )

            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium,
                    color = GodEyeColors.IvoryPure
                )
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodySmall,
                    color = GodEyeColors.IvorySoft
                )
            }

            Switch(
                checked = checked,
                onCheckedChange = onCheckedChange,
                colors = SwitchDefaults.colors(
                    checkedThumbColor = GodEyeColors.IvoryPure,
                    checkedTrackColor = GodEyeColors.SuccessGreen,
                    uncheckedThumbColor = GodEyeColors.IvorySoft,
                    uncheckedTrackColor = GodEyeColors.NavyDark
                )
            )
        }
    }
}

@Composable
private fun InfoCard(
    title: String,
    subtitle: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = GodEyeColors.NavyDark.copy(alpha = 0.3f)
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = GodEyeColors.NavyLight,
                modifier = Modifier.size(24.dp)
            )

            Column {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium,
                    color = GodEyeColors.IvoryPure
                )
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodySmall,
                    color = GodEyeColors.IvorySoft
                )
            }
        }
    }
}
