package com.rosetta.messenger.ui.settings

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChevronRight
import compose.icons.TablerIcons
import compose.icons.tablericons.ChevronLeft
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import com.rosetta.messenger.ui.onboarding.PrimaryBlueDark
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun SafetyScreen(
    isDarkTheme: Boolean,
    accountPublicKey: String,
    accountPrivateKey: String = "",
    onBack: () -> Unit,
    onBackupClick: () -> Unit,
    onDeleteAccount: () -> Unit
) {
    val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
    val surfaceColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color(0xFFF2F2F7)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val redColor = if (isDarkTheme) Color(0xFFFF8787) else Color(0xFFEF4444)
    val greenColor = if (isDarkTheme) Color(0xFF3FC158) else Color(0xFF34C759)
    
    val clipboardManager = LocalClipboardManager.current
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    // Copy states
    var copiedPublicKey by remember { mutableStateOf(false) }
    var copiedPrivateKey by remember { mutableStateOf(false) }
    var showDeleteConfirmation by remember { mutableStateOf(false) }
    
    val view = androidx.compose.ui.platform.LocalView.current
    if (!view.isInEditMode) {
        androidx.compose.runtime.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
            onDispose { insetsController.isAppearanceLightStatusBars = prev }
        }
    }

    // Handle back gesture
    BackHandler { onBack() }
    
    // Short display keys
    val shortPublicKey = if (accountPublicKey.length > 20) 
        accountPublicKey.take(20) else accountPublicKey
    val shortPrivateKey = if (accountPrivateKey.length > 20) 
        accountPrivateKey.take(20) else "B8zPXVMQrYkxaWE39v"

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(backgroundColor)
    ) {
        // 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 = "Safety",
                    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))

            // ═══════════════════════════════════════════════════════════════
            // Keys Section - Telegram style
            // ═══════════════════════════════════════════════════════════════
            TelegramSectionHeader("Keys", Color(0xFF8E8E93))
            
            TelegramCopyRow(
                label = "Public Key",
                value = shortPublicKey,
                fullValue = accountPublicKey,
                isCopied = copiedPublicKey,
                onCopy = {
                    clipboardManager.setText(AnnotatedString(accountPublicKey))
                    val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    val clip = ClipData.newPlainText("Public Key", accountPublicKey)
                    cm.setPrimaryClip(clip)
                    copiedPublicKey = true
                    scope.launch {
                        delay(2000)
                        copiedPublicKey = false
                    }
                },
                textColor = textColor,
                secondaryTextColor = secondaryTextColor,
                greenColor = greenColor,
                showDivider = true
            )

            TelegramCopyRow(
                label = "Private Key",
                value = shortPrivateKey,
                fullValue = accountPrivateKey,
                isCopied = copiedPrivateKey,
                onCopy = {
                    if (accountPrivateKey.isNotEmpty()) {
                        clipboardManager.setText(AnnotatedString(accountPrivateKey))
                        val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        val clip = ClipData.newPlainText("Private Key", accountPrivateKey)
                        cm.setPrimaryClip(clip)
                        copiedPrivateKey = true
                        scope.launch {
                            delay(2000)
                            copiedPrivateKey = false
                        }
                        scope.launch {
                            delay(30_000)
                            cm.setPrimaryClip(ClipData.newPlainText("", ""))
                        }
                    }
                },
                textColor = textColor,
                secondaryTextColor = secondaryTextColor,
                greenColor = greenColor,
                showDivider = false
            )

            TelegramInfoText(
                text = "Your private key is encrypted. Never share it with anyone.",
                secondaryTextColor = secondaryTextColor
            )

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

            // ═══════════════════════════════════════════════════════════════
            // Actions Section - Telegram style
            // ═══════════════════════════════════════════════════════════════
            TelegramActionRow(
                label = "Backup",
                onClick = onBackupClick,
                textColor = textColor,
                secondaryTextColor = secondaryTextColor,
                showDivider = true
            )

            TelegramActionRow(
                label = "Delete Account",
                onClick = { showDeleteConfirmation = true },
                textColor = redColor,
                secondaryTextColor = secondaryTextColor,
                showDivider = false
            )

            TelegramInfoText(
                text = "Deleting your account will permanently remove all data from this device and the server.",
                secondaryTextColor = secondaryTextColor
            )

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

    // Delete Account Confirmation Dialog
    if (showDeleteConfirmation) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirmation = false },
            containerColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
            title = {
                Text(
                    "Delete Account",
                    fontWeight = FontWeight.Bold,
                    color = textColor
                )
            },
            text = {
                Text(
                    "You are attempting to delete your account. Are you sure? This action cannot be undone.",
                    color = secondaryTextColor
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        showDeleteConfirmation = false
                        onDeleteAccount()
                    }
                ) { Text("Delete", color = Color(0xFFFF3B30)) }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirmation = false }) {
                    Text("Cancel", color = if (isDarkTheme) PrimaryBlueDark else PrimaryBlue)
                }
            }
        )
    }
}

@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 TelegramCopyRow(
    label: String,
    value: String,
    fullValue: String,
    isCopied: Boolean,
    onCopy: () -> Unit,
    textColor: Color,
    secondaryTextColor: Color,
    greenColor: Color,
    showDivider: Boolean
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onCopy)
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = label,
                fontSize = 16.sp,
                color = textColor
            )
            Text(
                text = if (isCopied) "Copied" else value,
                fontSize = 16.sp,
                color = if (isCopied) greenColor else secondaryTextColor
            )
        }
        if (showDivider) {
            Divider(
                color = if (textColor == Color.White) Color(0xFF3A3A3A) else Color(0xFFE0E0E0),
                thickness = 0.5.dp,
                modifier = Modifier.padding(start = 16.dp)
            )
        }
    }
}

@Composable
private fun TelegramActionRow(
    label: String,
    onClick: () -> Unit,
    textColor: Color,
    secondaryTextColor: Color,
    showDivider: Boolean
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onClick)
                .padding(horizontal = 16.dp, vertical = 14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = label,
                fontSize = 16.sp,
                color = textColor,
                modifier = Modifier.weight(1f)
            )
            Icon(
                imageVector = Icons.Filled.ChevronRight,
                contentDescription = null,
                tint = secondaryTextColor,
                modifier = Modifier.size(20.dp)
            )
        }
        if (showDivider) {
            Divider(
                color = if (textColor == Color.White) Color(0xFF3A3A3A) else Color(0xFFE0E0E0),
                thickness = 0.5.dp,
                modifier = Modifier.padding(start = 16.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
    )
}
