package com.rosetta.messenger.ui.settings

import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import compose.icons.TablerIcons
import compose.icons.tablericons.*
import com.rosetta.messenger.ui.icons.TelegramIcons
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.view.drawToBitmap
import com.rosetta.messenger.ui.components.AppleEmojiText
import kotlin.math.hypot
import kotlinx.coroutines.launch

private fun maxRevealRadius(center: Offset, bounds: IntSize): Float {
    if (bounds.width <= 0 || bounds.height <= 0) return 0f
    val width = bounds.width.toFloat()
    val height = bounds.height.toFloat()
    return maxOf(
        hypot(center.x, center.y),
        hypot(width - center.x, center.y),
        hypot(center.x, height - center.y),
        hypot(width - center.x, height - center.y)
    )
}

@Composable
fun ThemeScreen(
    isDarkTheme: Boolean,
    currentThemeMode: String,
    currentWallpaperId: String,
    onBack: () -> Unit,
    onThemeModeChange: (String) -> Unit,
    onWallpaperChange: (String) -> Unit
) {
    val view = LocalView.current
    if (!view.isInEditMode) {
        DisposableEffect(isDarkTheme) {
            val window = (view.context as android.app.Activity).window
            val insetsController = androidx.core.view.WindowCompat.getInsetsController(window, view)
            val prev = insetsController.isAppearanceLightStatusBars
            insetsController.isAppearanceLightStatusBars = !isDarkTheme
            window.statusBarColor = android.graphics.Color.TRANSPARENT
            onDispose { insetsController.isAppearanceLightStatusBars = prev }
        }
    }

    val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val scope = rememberCoroutineScope()
    val systemIsDark = isSystemInDarkTheme()

    // Theme mode: "light", "dark", "auto"
    var themeMode by remember { mutableStateOf(currentThemeMode) }
    val themeRevealRadius = remember { Animatable(0f) }
    var rootSize by remember { mutableStateOf(IntSize.Zero) }
    var themeRevealActive by remember { mutableStateOf(false) }
    var themeRevealToDark by remember { mutableStateOf(false) }
    var themeRevealCenter by remember { mutableStateOf(Offset.Zero) }
    var themeRevealSnapshot by remember { mutableStateOf<ImageBitmap?>(null) }
    var prewarmedBitmap by remember { mutableStateOf<android.graphics.Bitmap?>(null) }

    // Prewarm bitmap on screen appear
    LaunchedEffect(Unit) {
        kotlinx.coroutines.delay(300)
        prewarmedBitmap = runCatching { view.drawToBitmap() }.getOrNull()
    }
    var lightOptionCenter by remember { mutableStateOf<Offset?>(null) }
    var darkOptionCenter by remember { mutableStateOf<Offset?>(null) }
    var systemOptionCenter by remember { mutableStateOf<Offset?>(null) }
    var wallpaperId by remember { mutableStateOf(currentWallpaperId) }

    LaunchedEffect(currentThemeMode) {
        themeMode = currentThemeMode
    }

    LaunchedEffect(currentWallpaperId) {
        wallpaperId = currentWallpaperId
    }

    fun resolveThemeIsDark(mode: String): Boolean =
        when (mode) {
            "dark" -> true
            "light" -> false
            else -> systemIsDark
        }

    fun startThemeReveal(targetMode: String, centerHint: Offset?) {
        if (themeRevealActive || themeMode == targetMode) return
        val targetIsDark = resolveThemeIsDark(targetMode)
        if (targetIsDark == isDarkTheme || rootSize.width <= 0 || rootSize.height <= 0) {
            themeMode = targetMode
            onThemeModeChange(targetMode)
            return
        }

        val center =
            centerHint ?: Offset(rootSize.width * 0.85f, rootSize.height * 0.18f)
        val snapshotBitmap = prewarmedBitmap ?: runCatching { view.drawToBitmap() }.getOrNull()
        prewarmedBitmap = null
        if (snapshotBitmap == null) {
            themeMode = targetMode
            onThemeModeChange(targetMode)
            return
        }

        val maxRadius = maxRevealRadius(center, rootSize)
        if (maxRadius <= 0f) {
            themeMode = targetMode
            onThemeModeChange(targetMode)
            return
        }

        themeRevealActive = true
        themeRevealToDark = targetIsDark
        themeRevealCenter = center
        themeRevealSnapshot = snapshotBitmap.asImageBitmap()

        scope.launch {
            try {
                if (targetIsDark) {
                    themeRevealRadius.snapTo(0f)
                } else {
                    themeRevealRadius.snapTo(maxRadius)
                }
                themeMode = targetMode
                onThemeModeChange(targetMode)
                withFrameNanos { }
                themeRevealRadius.animateTo(
                    targetValue = if (targetIsDark) maxRadius else 0f,
                    animationSpec =
                        tween(
                            durationMillis = 400,
                            easing = CubicBezierEasing(0.45f, 0.05f, 0.55f, 0.95f)
                        )
                )
            } finally {
                themeRevealSnapshot = null
                themeRevealActive = false
            }
        }
    }
    
    // Handle back gesture
    BackHandler { onBack() }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .onSizeChanged { rootSize = it }
            .background(backgroundColor)
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            // Top Bar
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = backgroundColor
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding())
                        .padding(horizontal = 4.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onBack) {
                        Icon(
                            imageVector = TablerIcons.ChevronLeft,
                            contentDescription = "Back",
                            tint = textColor
                        )
                    }
                    Text(
                        text = "Theme",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = textColor,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }

            // Content
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
            ) {
                Spacer(modifier = Modifier.height(8.dp))

                // ═══════════════════════════════════════════════════════
                // CHAT PREVIEW - Message bubbles like in real chat
                // ═══════════════════════════════════════════════════════
                ChatPreview(isDarkTheme = isDarkTheme, wallpaperId = wallpaperId)

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

                // ═══════════════════════════════════════════════════════
                // MODE SELECTOR - Telegram style
                // ═══════════════════════════════════════════════════════
                TelegramSectionHeader("Appearance", secondaryTextColor)

                Column {
                    TelegramThemeOption(
                        icon = TablerIcons.Sun,
                        title = "Light",
                        isSelected = themeMode == "light",
                        onClick = { startThemeReveal("light", lightOptionCenter) },
                        textColor = textColor,
                        secondaryTextColor = secondaryTextColor,
                        showDivider = true,
                        isDarkTheme = isDarkTheme,
                        onCenterInRootChanged = { lightOptionCenter = it }
                    )

                    TelegramThemeOption(
                        icon = TablerIcons.Moon,
                        title = "Dark",
                        isSelected = themeMode == "dark",
                        onClick = { startThemeReveal("dark", darkOptionCenter) },
                        textColor = textColor,
                        secondaryTextColor = secondaryTextColor,
                        showDivider = true,
                        isDarkTheme = isDarkTheme,
                        onCenterInRootChanged = { darkOptionCenter = it }
                    )

                    TelegramThemeOption(
                        icon = TablerIcons.DeviceMobile,
                        title = "System",
                        isSelected = themeMode == "auto",
                        onClick = { startThemeReveal("auto", systemOptionCenter) },
                        textColor = textColor,
                        secondaryTextColor = secondaryTextColor,
                        showDivider = false,
                        isDarkTheme = isDarkTheme,
                        onCenterInRootChanged = { systemOptionCenter = it }
                    )
                }

                TelegramInfoText(
                    text = "System mode automatically switches between light and dark themes based on your device settings.",
                    secondaryTextColor = secondaryTextColor
                )

                TelegramSectionHeader("Chat Wallpaper", secondaryTextColor)

                WallpaperSelectorRow(
                    isDarkTheme = isDarkTheme,
                    selectedWallpaperId = wallpaperId,
                    wallpapers = ThemeWallpapers.forTheme(isDarkTheme),
                    textColor = textColor,
                    secondaryTextColor = secondaryTextColor,
                    onWallpaperSelected = { selectedId ->
                        if (selectedId != wallpaperId) {
                            wallpaperId = selectedId
                            onWallpaperChange(selectedId)
                        }
                    }
                )

                TelegramInfoText(
                    text =
                        if (isDarkTheme) {
                            "Showing wallpapers for dark theme. Switch to light mode to choose light wallpapers."
                        } else {
                            "Showing wallpapers for light theme. Switch to dark mode to choose dark wallpapers."
                        },
                    secondaryTextColor = secondaryTextColor
                )

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

        if (themeRevealActive) {
            val snapshot = themeRevealSnapshot
            if (snapshot != null) {
                Canvas(
                    modifier =
                        Modifier.fillMaxSize()
                            .graphicsLayer(
                                compositingStrategy = CompositingStrategy.Offscreen
                            )
                ) {
                    val destinationSize =
                        IntSize(
                            width = size.width.toInt(),
                            height = size.height.toInt()
                        )
                    if (themeRevealToDark) {
                        drawImage(
                            image = snapshot,
                            srcOffset = IntOffset.Zero,
                            srcSize = IntSize(snapshot.width, snapshot.height),
                            dstOffset = IntOffset.Zero,
                            dstSize = destinationSize
                        )
                        drawCircle(
                            color = Color.Transparent,
                            radius = themeRevealRadius.value,
                            center = themeRevealCenter,
                            blendMode = BlendMode.Clear
                        )
                    } else {
                        val radius = themeRevealRadius.value
                        if (radius > 0f) {
                            val clipCirclePath =
                                Path().apply {
                                    addOval(
                                        Rect(
                                            left = themeRevealCenter.x - radius,
                                            top = themeRevealCenter.y - radius,
                                            right = themeRevealCenter.x + radius,
                                            bottom = themeRevealCenter.y + radius
                                        )
                                    )
                                }
                            clipPath(clipCirclePath) {
                                drawImage(
                                    image = snapshot,
                                    srcOffset = IntOffset.Zero,
                                    srcSize = IntSize(snapshot.width, snapshot.height),
                                    dstOffset = IntOffset.Zero,
                                    dstSize = destinationSize
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun TelegramSectionHeader(title: String, color: Color) {
    Text(
        text = title,
        fontSize = 15.sp,
        fontWeight = FontWeight.Medium,
        color = color,
        modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)
    )
}

@Composable
private fun TelegramThemeOption(
    icon: ImageVector,
    title: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    textColor: Color,
    secondaryTextColor: Color,
    showDivider: Boolean,
    isDarkTheme: Boolean,
    onCenterInRootChanged: ((Offset) -> Unit)? = null
) {
    val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE0E0E0)
    
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onClick)
                .onGloballyPositioned { coords ->
                    val pos = coords.positionInRoot()
                    onCenterInRootChanged?.invoke(
                        Offset(
                            x = pos.x + coords.size.width / 2f,
                            y = pos.y + coords.size.height / 2f
                        )
                    )
                }
                .padding(horizontal = 16.dp, vertical = 14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = secondaryTextColor,
                modifier = Modifier.size(24.dp)
            )

            Spacer(modifier = Modifier.width(16.dp))

            Text(
                text = title,
                fontSize = 16.sp,
                color = textColor,
                modifier = Modifier.weight(1f)
            )

            // Radio button
            if (isSelected) {
                Icon(
                    painter = TelegramIcons.Done,
                    contentDescription = null,
                    tint = Color(0xFF007AFF),
                    modifier = Modifier.size(20.dp)
                )
            }
        }
        
        if (showDivider) {
            Divider(
                color = dividerColor,
                thickness = 0.5.dp,
                modifier = Modifier.padding(start = 56.dp)
            )
        }
    }
}

@Composable
private fun TelegramInfoText(text: String, secondaryTextColor: Color) {
    Text(
        text = text,
        fontSize = 13.sp,
        color = secondaryTextColor,
        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
        lineHeight = 18.sp
    )
}

@Composable
private fun WallpaperSelectorRow(
    isDarkTheme: Boolean,
    selectedWallpaperId: String,
    wallpapers: List<ThemeWallpaper>,
    textColor: Color,
    secondaryTextColor: Color,
    onWallpaperSelected: (String) -> Unit
) {
    LazyRow(
        modifier = Modifier.fillMaxWidth(),
        contentPadding = PaddingValues(horizontal = 16.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        item(key = "none") {
            WallpaperSelectorItem(
                title = "No wallpaper",
                wallpaperResId = null,
                isSelected = selectedWallpaperId.isBlank(),
                isDarkTheme = isDarkTheme,
                textColor = textColor,
                secondaryTextColor = secondaryTextColor,
                onClick = { onWallpaperSelected("") }
            )
        }

        items(items = wallpapers, key = { it.id }) { wallpaper ->
            WallpaperSelectorItem(
                title = wallpaper.name,
                wallpaperResId = wallpaper.drawableRes,
                isSelected = wallpaper.id == selectedWallpaperId,
                isDarkTheme = isDarkTheme,
                textColor = textColor,
                secondaryTextColor = secondaryTextColor,
                onClick = { onWallpaperSelected(wallpaper.id) }
            )
        }
    }
}

@Composable
private fun WallpaperSelectorItem(
    title: String,
    wallpaperResId: Int?,
    isSelected: Boolean,
    isDarkTheme: Boolean,
    textColor: Color,
    secondaryTextColor: Color,
    onClick: () -> Unit
) {
    val borderColor = if (isSelected) Color(0xFF007AFF) else secondaryTextColor.copy(alpha = 0.35f)

    Column(
        modifier =
            Modifier.width(100.dp).clickable(onClick = onClick),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Surface(
            modifier = Modifier.size(width = 100.dp, height = 76.dp),
            shape = RoundedCornerShape(10.dp),
            color = if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
            border = androidx.compose.foundation.BorderStroke(if (isSelected) 2.dp else 1.dp, borderColor)
        ) {
            if (wallpaperResId != null) {
                Image(
                    painter = painterResource(id = wallpaperResId),
                    contentDescription = title,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            } else {
                Box(
                    modifier =
                        Modifier.fillMaxSize()
                            .background(if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFF2F2F7))
                )
            }
        }

        Text(
            text = title,
            fontSize = 12.sp,
            color = if (isSelected) textColor else secondaryTextColor,
            modifier = Modifier.padding(top = 8.dp),
            maxLines = 1
        )
    }
}

// ═══════════════════════════════════════════════════════════════════
// 💬 CHAT PREVIEW - Real message bubbles preview
// ═══════════════════════════════════════════════════════════════════

@Composable
private fun ChatPreview(isDarkTheme: Boolean, wallpaperId: String) {
    val wallpaperResId = remember(wallpaperId) { ThemeWallpapers.drawableResOrNull(wallpaperId) }
    val hasWallpaper = wallpaperResId != null
    val chatBgColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFF0F0F0)
    // Message colors matching real ChatDetailScreen
    val myBubbleColor = Color(0xFF248AE6) // PrimaryBlue - same for both themes
    val otherBubbleColor =
        if (hasWallpaper) {
            if (isDarkTheme) Color(0xFF2C2E33) else Color.White
        } else {
            if (isDarkTheme) Color(0xFF212121) else Color(0xFFF5F5F5)
        }
    val myTextColor = Color.White // White text on blue bubble
    val otherTextColor = if (isDarkTheme) Color.White else Color.Black
    val myTimeColor = Color.White // White time on blue bubble (matches real chat)
    val otherTimeColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val myCheckColor = Color.White
    
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .height(230.dp),
        color = chatBgColor,
        shape = RoundedCornerShape(16.dp)
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            if (wallpaperResId != null) {
                Image(
                    painter = painterResource(id = wallpaperResId),
                    contentDescription = "Chat wallpaper preview",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            }

            Column(
                modifier = Modifier.fillMaxSize().padding(12.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // Incoming message
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Start
                ) {
                    MessageBubble(
                        text = "Hey! How's it going? 👋",
                        time = "10:42",
                        isMe = false,
                        bubbleColor = otherBubbleColor,
                        textColor = otherTextColor,
                        timeColor = otherTimeColor
                    )
                }

                // Outgoing message
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    MessageBubble(
                        text = "Hey! All good, just checking out this new theme 😊",
                        time = "10:43",
                        isMe = true,
                        bubbleColor = myBubbleColor,
                        textColor = myTextColor,
                        timeColor = myTimeColor,
                        checkmarkColor = myCheckColor
                    )
                }

                // Incoming message
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Start
                ) {
                    MessageBubble(
                        text = "Nice! Looks great! 🔥",
                        time = "10:44",
                        isMe = false,
                        bubbleColor = otherBubbleColor,
                        textColor = otherTextColor,
                        timeColor = otherTimeColor
                    )
                }
            }
        }
    }
}

@Composable
private fun MessageBubble(
    text: String,
    time: String,
    isMe: Boolean,
    bubbleColor: Color,
    textColor: Color,
    timeColor: Color,
    checkmarkColor: Color = Color(0xFF4FC3F7)
) {
    Surface(
        color = bubbleColor,
        shape = RoundedCornerShape(
            topStart = 16.dp,
            topEnd = 16.dp,
            bottomStart = if (isMe) 16.dp else 4.dp,
            bottomEnd = if (isMe) 4.dp else 16.dp
        ),
        shadowElevation = 1.dp
    ) {
        Column(
            modifier = Modifier
                .widthIn(max = 260.dp)
                .padding(horizontal = 12.dp, vertical = 8.dp)
        ) {
            AppleEmojiText(
                text = text,
                fontSize = 15.sp,
                color = textColor
            )
            
            Row(
                modifier = Modifier.align(Alignment.End),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(3.dp)
            ) {
                Text(
                    text = time,
                    fontSize = 11.sp,
                    color = timeColor.copy(alpha = 0.7f)
                )
                
                if (isMe) {
                    // Read checkmarks (DoneAll icon like in real chat)
                    Icon(
                        painter = TelegramIcons.Done,
                        contentDescription = null,
                        tint = checkmarkColor,
                        modifier = Modifier.size(14.dp)
                    )
                }
            }
        }
    }
}
