package com.rosetta.messenger.ui.chats.components

import android.view.HapticFeedbackConstants
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.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import compose.icons.TablerIcons
import compose.icons.tablericons.Bug
import com.rosetta.messenger.ui.icons.TelegramIcons
import kotlinx.coroutines.launch

/**
 * 🐛 BottomSheet для отображения debug логов протокола
 *
 * Показывает логи отправки/получения сообщений для дебага.
 * Использует ProtocolManager.debugLogs как источник данных.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DebugLogsBottomSheet(
    logs: List<String>,
    isDarkTheme: Boolean,
    onDismiss: () -> Unit,
    onClearLogs: () -> Unit
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
    val scope = rememberCoroutineScope()
    val view = LocalView.current
    val listState = rememberLazyListState()

    // Colors
    val backgroundColor = if (isDarkTheme) Color(0xFF1C1C1E) else Color.White
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)

    // Haptic feedback при открытии
    LaunchedEffect(Unit) {
        view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
    }

    // Авто-скролл вниз при новых логах
    LaunchedEffect(logs.size) {
        if (logs.isNotEmpty()) {
            listState.animateScrollToItem(logs.size - 1)
        }
    }

    // Плавное затемнение статус бара
    DisposableEffect(Unit) {
        if (!view.isInEditMode) {
            val window = (view.context as? android.app.Activity)?.window
            val originalStatusBarColor = window?.statusBarColor ?: 0
            val scrimColor = android.graphics.Color.argb(153, 0, 0, 0)

            val fadeInAnimator = android.animation.ValueAnimator.ofArgb(originalStatusBarColor, scrimColor).apply {
                duration = 200
                addUpdateListener { animator ->
                    window?.statusBarColor = animator.animatedValue as Int
                }
            }
            fadeInAnimator.start()

            onDispose {
                val fadeOutAnimator = android.animation.ValueAnimator.ofArgb(scrimColor, originalStatusBarColor).apply {
                    duration = 150
                    addUpdateListener { animator ->
                        window?.statusBarColor = animator.animatedValue as Int
                    }
                }
                fadeOutAnimator.start()
            }
        } else {
            onDispose { }
        }
    }

    fun dismissWithAnimation() {
        scope.launch {
            sheetState.hide()
            onDismiss()
        }
    }

    ModalBottomSheet(
        onDismissRequest = { dismissWithAnimation() },
        sheetState = sheetState,
        containerColor = backgroundColor,
        scrimColor = Color.Black.copy(alpha = 0.6f),
        dragHandle = {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(8.dp))
                Box(
                    modifier = Modifier
                        .width(36.dp)
                        .height(5.dp)
                        .clip(RoundedCornerShape(2.5.dp))
                        .background(if (isDarkTheme) Color(0xFF4A4A4A) else Color(0xFFD1D1D6))
                )
                Spacer(modifier = Modifier.height(16.dp))
            }
        },
        shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        modifier = Modifier.statusBarsPadding()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .navigationBarsPadding()
        ) {
            // Header
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Иконка и заголовок
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        TablerIcons.Bug,
                        contentDescription = null,
                        tint = PrimaryBlue,
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Column {
                        Text(
                            text = "Debug Logs",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = textColor
                        )
                        Text(
                            text = "${logs.size} log entries",
                            fontSize = 14.sp,
                            color = secondaryTextColor
                        )
                    }
                }

                // Кнопки
                Row {
                    IconButton(onClick = onClearLogs) {
                        Icon(
                            painter = TelegramIcons.Delete,
                            contentDescription = "Clear logs",
                            tint = secondaryTextColor.copy(alpha = 0.6f),
                            modifier = Modifier.size(22.dp)
                        )
                    }
                    IconButton(onClick = { dismissWithAnimation() }) {
                        Icon(
                            Icons.Default.Close,
                            contentDescription = "Close",
                            tint = secondaryTextColor.copy(alpha = 0.6f),
                            modifier = Modifier.size(22.dp)
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(12.dp))
            Divider(color = dividerColor, thickness = 0.5.dp)

            // Контент
            if (logs.isEmpty()) {
                // Empty state
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "No logs yet.\nLogs will appear here during messaging.",
                        fontSize = 14.sp,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center
                    )
                }
            } else {
                // Список логов
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 300.dp, max = 500.dp)
                        .padding(horizontal = 8.dp, vertical = 8.dp)
                ) {
                    items(logs) { log ->
                        DebugLogItem(log = log, isDarkTheme = isDarkTheme)
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))
        }
    }
}

/**
 * Элемент лога с цветовой кодировкой
 */
@Composable
private fun DebugLogItem(
    log: String,
    isDarkTheme: Boolean
) {
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val successColor = Color(0xFF34C759)
    val errorColor = Color(0xFFFF3B30)
    val purpleColor = Color(0xFFAF52DE)
    val heartbeatColor = Color(0xFFFF9500)
    val messageColor = PrimaryBlue

    // Определяем цвет по содержимому лога
    val logColor = when {
        log.contains("✅") || log.contains("SUCCESS") -> successColor
        log.contains("❌") || log.contains("ERROR") || log.contains("FAILED") -> errorColor
        log.contains("🔄") || log.contains("STATE") -> purpleColor
        log.contains("💓") || log.contains("💔") -> heartbeatColor
        log.contains("📥") || log.contains("📤") || log.contains("📨") -> messageColor
        else -> textColor.copy(alpha = 0.85f)
    }

    Text(
        text = log,
        fontSize = 12.sp,
        fontFamily = FontFamily.Monospace,
        color = logColor,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp, horizontal = 8.dp)
    )
}
