package com.rosetta.messenger.ui.auth

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
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.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.crypto.CryptoManager
import com.rosetta.messenger.data.AccountManager
import com.rosetta.messenger.data.DecryptedAccount
import com.rosetta.messenger.data.EncryptedAccount
import com.rosetta.messenger.di.SessionCoordinator
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SetPasswordScreen(
        seedPhrase: List<String>,
        isDarkTheme: Boolean,
        isImportMode: Boolean = false,
        accountManager: AccountManager,
        sessionCoordinator: SessionCoordinator,
        onBack: () -> Unit,
        onAccountCreated: (DecryptedAccount) -> Unit
) {
    val backgroundColor = if (isDarkTheme) AuthBackground else AuthBackgroundLight
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF8E8E93)
    val fieldBackground = if (isDarkTheme) Color(0xFF2C2C2E) else Color(0xFFF2F2F7)

    val scope = rememberCoroutineScope()

    var password by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var passwordVisible by remember { mutableStateOf(false) }
    var confirmPasswordVisible by remember { mutableStateOf(false) }
    var isCreating by remember { mutableStateOf(false) }
    var error by remember { mutableStateOf<String?>(null) }

    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as android.app.Activity).window
            val insetsController = androidx.core.view.WindowCompat.getInsetsController(window, view)
            insetsController.isAppearanceLightStatusBars = false
            window.statusBarColor = android.graphics.Color.TRANSPARENT
        }
    }

    val passwordsMatch = password == confirmPassword && password.isNotEmpty()
    val isPasswordWeak = password.isNotEmpty() && password.length < 6
    val canContinue = passwordsMatch && !isCreating

    Scaffold(
        containerColor = backgroundColor,
        topBar = {
            TopAppBar(
                title = {},
                navigationIcon = {
                    IconButton(onClick = onBack, enabled = !isCreating) {
                        Icon(
                            imageVector = TablerIcons.ChevronLeft,
                            contentDescription = "Back",
                            tint = textColor
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .imePadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 24.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(12.dp))

            // Lock icon
            Box(
                modifier = Modifier
                    .size(56.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(PrimaryBlue.copy(alpha = 0.1f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    TablerIcons.Lock,
                    contentDescription = null,
                    tint = PrimaryBlue,
                    modifier = Modifier.size(28.dp)
                )
            }

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

            Text(
                text = if (isImportMode) "Recover Account" else "Protect Your Account",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = textColor
            )

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

            Text(
                text = "This password encrypts your keys locally.\nYou'll need it to unlock Rosetta.",
                fontSize = 14.sp,
                color = secondaryTextColor,
                textAlign = TextAlign.Center,
                lineHeight = 20.sp
            )

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

            // Password field — clean Telegram style
            TextField(
                value = password,
                onValueChange = { password = it; error = null },
                placeholder = { Text("Password", color = secondaryTextColor) },
                singleLine = true,
                visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                trailingIcon = {
                    IconButton(onClick = { passwordVisible = !passwordVisible }) {
                        Icon(
                            imageVector = if (passwordVisible) TablerIcons.EyeOff else TablerIcons.Eye,
                            contentDescription = null,
                            tint = secondaryTextColor,
                            modifier = Modifier.size(20.dp)
                        )
                    }
                },
                modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)),
                colors = TextFieldDefaults.colors(
                    focusedTextColor = textColor,
                    unfocusedTextColor = textColor,
                    focusedContainerColor = fieldBackground,
                    unfocusedContainerColor = fieldBackground,
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    cursorColor = PrimaryBlue
                ),
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Password,
                    imeAction = ImeAction.Next
                )
            )

            // Strength bar
            if (password.isNotEmpty()) {
                Spacer(modifier = Modifier.height(8.dp))
                val strength = when {
                    password.length < 6 -> 0.25f
                    password.length < 10 -> 0.6f
                    else -> 1f
                }
                val strengthColor = when {
                    password.length < 6 -> Color(0xFFE53935)
                    password.length < 10 -> Color(0xFFFFA726)
                    else -> Color(0xFF4CAF50)
                }
                val strengthLabel = when {
                    password.length < 6 -> "Weak"
                    password.length < 10 -> "Medium"
                    else -> "Strong"
                }
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .height(3.dp)
                            .clip(RoundedCornerShape(2.dp))
                            .background(fieldBackground)
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxHeight()
                                .fillMaxWidth(strength)
                                .clip(RoundedCornerShape(2.dp))
                                .background(strengthColor)
                        )
                    }
                    Text(
                        text = strengthLabel,
                        fontSize = 12.sp,
                        color = strengthColor
                    )
                }
            }

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

            // Confirm password field
            TextField(
                value = confirmPassword,
                onValueChange = { confirmPassword = it; error = null },
                placeholder = { Text("Confirm password", color = secondaryTextColor) },
                singleLine = true,
                visualTransformation = if (confirmPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                trailingIcon = {
                    IconButton(onClick = { confirmPasswordVisible = !confirmPasswordVisible }) {
                        Icon(
                            imageVector = if (confirmPasswordVisible) TablerIcons.EyeOff else TablerIcons.Eye,
                            contentDescription = null,
                            tint = secondaryTextColor,
                            modifier = Modifier.size(20.dp)
                        )
                    }
                },
                isError = confirmPassword.isNotEmpty() && !passwordsMatch,
                modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)),
                colors = TextFieldDefaults.colors(
                    focusedTextColor = textColor,
                    unfocusedTextColor = textColor,
                    focusedContainerColor = fieldBackground,
                    unfocusedContainerColor = fieldBackground,
                    errorContainerColor = fieldBackground,
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    errorIndicatorColor = Color.Transparent,
                    cursorColor = PrimaryBlue
                ),
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Password,
                    imeAction = ImeAction.Done
                )
            )

            // Match status
            if (confirmPassword.isNotEmpty()) {
                Spacer(modifier = Modifier.height(6.dp))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    val matchColor = if (passwordsMatch) Color(0xFF4CAF50) else Color(0xFFE53935)
                    Icon(
                        imageVector = if (passwordsMatch) TablerIcons.Check else TablerIcons.X,
                        contentDescription = null,
                        tint = matchColor,
                        modifier = Modifier.size(14.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = if (passwordsMatch) "Passwords match" else "Passwords don't match",
                        fontSize = 12.sp,
                        color = matchColor
                    )
                }
            }

            // Error
            error?.let {
                Spacer(modifier = Modifier.height(12.dp))
                Text(text = it, fontSize = 13.sp, color = Color(0xFFE53935), textAlign = TextAlign.Center)
            }

            Spacer(modifier = Modifier.weight(1f))

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

            // Create button
            Button(
                onClick = {
                    if (!passwordsMatch) {
                        error = "Passwords don't match"
                        return@Button
                    }
                    isCreating = true
                    scope.launch {
                        try {
                            val keyPair = CryptoManager.generateKeyPairFromSeed(seedPhrase)
                            val encryptedPrivateKey = CryptoManager.encryptWithPassword(keyPair.privateKey, password)
                            val encryptedSeedPhrase = CryptoManager.encryptWithPassword(seedPhrase.joinToString(" "), password)
                            val truncatedKey = "${keyPair.publicKey.take(6)}...${keyPair.publicKey.takeLast(4)}"
                            val account = EncryptedAccount(
                                publicKey = keyPair.publicKey,
                                encryptedPrivateKey = encryptedPrivateKey,
                                encryptedSeedPhrase = encryptedSeedPhrase,
                                name = truncatedKey
                            )
                            accountManager.saveAccount(account)
                            val privateKeyHash = CryptoManager.generatePrivateKeyHash(keyPair.privateKey)
                            val decryptedAccount = DecryptedAccount(
                                publicKey = keyPair.publicKey,
                                privateKey = keyPair.privateKey,
                                seedPhrase = seedPhrase,
                                privateKeyHash = privateKeyHash,
                                name = truncatedKey
                            )
                            sessionCoordinator.bootstrapAuthenticatedSession(
                                account = decryptedAccount,
                                reason = "set_password"
                            )
                            onAccountCreated(decryptedAccount)
                        } catch (e: Exception) {
                            error = "Failed to create account: ${e.message}"
                            isCreating = false
                        }
                    }
                },
                enabled = canContinue,
                modifier = Modifier.fillMaxWidth().height(50.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = PrimaryBlue,
                    contentColor = Color.White,
                    disabledContainerColor = PrimaryBlue.copy(alpha = 0.4f),
                    disabledContentColor = Color.White.copy(alpha = 0.5f)
                ),
                shape = RoundedCornerShape(12.dp)
            ) {
                if (isCreating) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(22.dp),
                        color = Color.White,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text(
                        text = if (isImportMode) "Recover Account" else "Create Account",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }

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