package com.example.godeye.ui.dialogs

import android.app.Dialog
import android.os.Bundle
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
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.Brush
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.fragment.app.DialogFragment
import com.example.godeye.models.CameraRequest
import com.example.godeye.ui.theme.GodEyeColors
import com.example.godeye.ui.theme.GodEyeTheme

/**
 * CameraRequestDialog - диалог запроса доступа к камере согласно ТЗ
 * Отображает информацию об операторе и запрашиваемой камере
 */
class CameraRequestDialog : DialogFragment() {

    private var cameraRequest: CameraRequest? = null
    private var onAccept: (() -> Unit)? = null
    private var onReject: (() -> Unit)? = null
    private var autoAccept: Boolean = false

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext())
        dialog.setContentView(ComposeView(requireContext()).apply {
            setContent {
                GodEyeTheme {
                    CameraRequestDialogContent(
                        cameraRequest = cameraRequest,
                        autoAccept = autoAccept,
                        onAccept = {
                            onAccept?.invoke()
                            dismiss()
                        },
                        onReject = {
                            onReject?.invoke()
                            dismiss()
                        }
                    )
                }
            }
        })

        dialog.setCancelable(false) // Пользователь должен явно принять решение
        return dialog
    }

    companion object {
        fun newInstance(
            request: CameraRequest,
            autoAccept: Boolean = false,
            onAccept: () -> Unit,
            onReject: () -> Unit
        ): CameraRequestDialog {
            return CameraRequestDialog().apply {
                this.cameraRequest = request
                this.autoAccept = autoAccept
                this.onAccept = onAccept
                this.onReject = onReject
            }
        }
    }
}

@Composable
private fun CameraRequestDialogContent(
    cameraRequest: CameraRequest?,
    autoAccept: Boolean,
    onAccept: () -> Unit,
    onReject: () -> Unit
) {
    if (cameraRequest == null) return

    // Автоматическое принятие если включено
    if (autoAccept) {
        LaunchedEffect(Unit) {
            kotlinx.coroutines.delay(500) // Небольшая задержка для показа диалога
            onAccept()
        }
    }

    Dialog(onDismissRequest = { /* Нельзя закрыть без выбора */ }) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            shape = RoundedCornerShape(24.dp),
            colors = CardDefaults.cardColors(
                containerColor = GodEyeColors.BlackSoft
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 16.dp)
        ) {
            Column(
                modifier = Modifier
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                GodEyeColors.NavyDark.copy(alpha = 0.3f),
                                GodEyeColors.BlackSoft
                            )
                        )
                    )
                    .padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // Иконка оператора
                Box(
                    modifier = Modifier
                        .size(80.dp)
                        .background(
                            Brush.radialGradient(
                                colors = listOf(
                                    GodEyeColors.NavyLight.copy(alpha = 0.3f),
                                    GodEyeColors.NavyDark.copy(alpha = 0.1f)
                                )
                            ),
                            RoundedCornerShape(50)
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        Icons.Default.Person,
                        contentDescription = null,
                        modifier = Modifier.size(40.dp),
                        tint = GodEyeColors.NavyLight
                    )
                }

                // Заголовок
                Text(
                    text = "Запрос доступа к камере",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Medium,
                    color = GodEyeColors.IvoryPure
                )

                // Информация о запросе согласно ТЗ
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = GodEyeColors.BlackMedium.copy(alpha = 0.5f)
                    ),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        InfoRow(
                            label = "Оператор",
                            value = cameraRequest.operatorId,
                            icon = Icons.Default.Person
                        )

                        InfoRow(
                            label = "Камера",
                            value = getCameraDisplayName(cameraRequest.cameraType),
                            icon = Icons.Default.Videocam
                        )

                        InfoRow(
                            label = "Session ID",
                            value = cameraRequest.sessionId.take(12) + "...",
                            icon = Icons.Default.Key
                        )
                    }
                }

                // Описание запроса
                Text(
                    text = "Оператор ${cameraRequest.operatorId} запрашивает доступ к камере ${getCameraDisplayName(cameraRequest.cameraType)}",
                    style = MaterialTheme.typography.bodyMedium,
                    color = GodEyeColors.IvorySoft,
                    lineHeight = MaterialTheme.typography.bodyMedium.lineHeight * 1.4
                )

                // Индикатор автоматического принятия
                if (autoAccept) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp,
                            color = GodEyeColors.SuccessGreen
                        )
                        Text(
                            text = "Автоматическое принятие...",
                            style = MaterialTheme.typography.bodySmall,
                            color = GodEyeColors.SuccessGreen
                        )
                    }
                }

                // Кнопки действий согласно ТЗ
                if (!autoAccept) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        // Кнопка "Отклонить"
                        OutlinedButton(
                            onClick = onReject,
                            modifier = Modifier.weight(1f),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = GodEyeColors.RecordRed
                            ),
                            border = ButtonDefaults.outlinedButtonBorder.copy(
                                brush = Brush.horizontalGradient(
                                    colors = listOf(
                                        GodEyeColors.RecordRed,
                                        GodEyeColors.RecordRed.copy(alpha = 0.7f)
                                    )
                                )
                            ),
                            shape = RoundedCornerShape(12.dp)
                        ) {
                            Icon(
                                Icons.Default.Close,
                                contentDescription = null,
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text("Отклонить")
                        }

                        // Кнопка "Разрешить"
                        Button(
                            onClick = onAccept,
                            modifier = Modifier.weight(1f),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = GodEyeColors.SuccessGreen
                            ),
                            shape = RoundedCornerShape(12.dp)
                        ) {
                            Icon(
                                Icons.Default.Check,
                                contentDescription = null,
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text(
                                "Разрешить",
                                color = GodEyeColors.IvoryPure
                            )
                        }
                    }
                }

                // Опция "Запомнить для этого оператора" согласно ТЗ
                if (!autoAccept) {
                    var rememberChoice by remember { mutableStateOf(false) }

                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Checkbox(
                            checked = rememberChoice,
                            onCheckedChange = { rememberChoice = it },
                            colors = CheckboxDefaults.colors(
                                checkedColor = GodEyeColors.NavyLight,
                                uncheckedColor = GodEyeColors.IvorySoft
                            )
                        )
                        Text(
                            text = "Запомнить для этого оператора",
                            style = MaterialTheme.typography.bodySmall,
                            color = GodEyeColors.IvorySoft
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun InfoRow(
    label: String,
    value: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Icon(
            icon,
            contentDescription = null,
            modifier = Modifier.size(20.dp),
            tint = GodEyeColors.NavyLight
        )

        Column {
            Text(
                text = label,
                style = MaterialTheme.typography.bodySmall,
                color = GodEyeColors.IvorySoft
            )
            Text(
                text = value,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.Medium,
                color = GodEyeColors.IvoryPure
            )
        }
    }
}

/**
 * Получение человекочитаемого названия камеры согласно ТЗ
 */
private fun getCameraDisplayName(cameraType: String): String {
    return when (cameraType) {
        "back" -> "Основная камера"
        "front" -> "Фронтальная камера"
        "ultra_wide" -> "Широкоугольная камера"
        "telephoto" -> "Телеобъектив"
        else -> "Камера ($cameraType)"
    }
}
