package dev.zxq5.chatapp.android.feature.settings

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.graphics.asImageBitmap
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import android.util.Base64
import android.graphics.BitmapFactory
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.style.TextAlign
import dev.zxq5.chatapp.android.api.model.InviteRequest
import kotlin.time.Duration.Companion.days
import kotlin.time.ExperimentalTime
import kotlin.time.Instant

@OptIn(ExperimentalMaterial3Api::class, ExperimentalTime::class)
@Composable
fun SettingsScreen(
    viewModel: SettingsViewModel,
    onLogout: () -> Unit
) {
    val is2faEnabled by viewModel.is2faEnabled.collectAsState()
    val totpQr by viewModel.totpQr.collectAsState()
    val settingsError by viewModel.settingsError.collectAsState()
    val isSuccessState by viewModel.isSuccessState.collectAsState()
    val totpError by viewModel.totpError.collectAsState()
    val lastInviteCode by viewModel.lastInviteCode.collectAsState()
    
    LaunchedEffect(Unit) {
        viewModel.clearMessages()
        viewModel.fetchTotpStatus()
    }

    Scaffold(
        containerColor = MaterialTheme.colorScheme.background,
        topBar = {
            TopAppBar(
                title = { 
                    Text(
                        "settings", 
                        style = MaterialTheme.typography.titleLarge,
                        color = MaterialTheme.colorScheme.onSurface
                    ) 
                },
                windowInsets = androidx.compose.foundation.layout.WindowInsets(0, 0, 0, 0),
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            SettingsSection(title = "profile") {
                var displayName by remember { mutableStateOf("") }
                var username by remember { mutableStateOf("") }

                SettingsField(
                    label = "display name",
                    value = displayName,
                    onValueChange = { displayName = it },
                    buttonLabel = "update",
                    isSuccess = isSuccessState["display_name"] == true,
                    onClick = { viewModel.updateDisplayName(displayName.ifBlank { null }) }
                )

                Spacer(Modifier.height(16.dp))

                SettingsField(
                    label = "username",
                    value = username,
                    onValueChange = { username = it },
                    buttonLabel = "update",
                    isSuccess = isSuccessState["username"] == true,
                    onClick = { if (username.isNotBlank()) viewModel.updateUsername(username) }
                )
            }

            SettingsSection(title = "security") {
                var oldPassword by remember { mutableStateOf("") }
                var newPassword by remember { mutableStateOf("") }

                Text("change password", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 8.dp))
                OutlinedTextField(
                    value = oldPassword,
                    onValueChange = { oldPassword = it },
                    label = { Text("old password") },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(8.dp)
                )
                Spacer(Modifier.height(8.dp))
                OutlinedTextField(
                    value = newPassword,
                    onValueChange = { newPassword = it },
                    label = { Text("new password") },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(8.dp)
                )
                Spacer(Modifier.height(12.dp))
                SuccessButton(
                    onClick = { 
                        viewModel.changePassword(oldPassword, newPassword)
                        oldPassword = ""
                        newPassword = ""
                    },
                    label = "update password",
                    isSuccess = isSuccessState["password"] == true,
                    enabled = oldPassword.isNotEmpty() && newPassword.isNotEmpty(),
                    modifier = Modifier.fillMaxWidth()
                )

                HorizontalDivider(modifier = Modifier.padding(vertical = 16.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f))

                var show2faSetup by remember { mutableStateOf(false) }
                var setupPassword by remember { mutableStateOf("") }
                
                var show2faDisable by remember { mutableStateOf(false) }
                var disablePassword by remember { mutableStateOf("") }
                var disableCode by remember { mutableStateOf("") }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text("two-factor authentication", style = MaterialTheme.typography.bodyLarge)
                        Text(
                            if (is2faEnabled) "enabled" else "disabled",
                            style = MaterialTheme.typography.labelSmall,
                            color = if (is2faEnabled) Color.Green.copy(alpha = 0.7f) else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
                        )
                    }
                    
                    if (!is2faEnabled) {
                        Button(
                            onClick = { 
                                show2faSetup = !show2faSetup
                                if (!show2faSetup) setupPassword = ""
                            },
                            shape = RoundedCornerShape(8.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), contentColor = MaterialTheme.colorScheme.onSurface)
                        ) {
                            Text(if (show2faSetup) "cancel" else "setup", style = MaterialTheme.typography.labelSmall)
                        }
                    } else {
                        SuccessButton(
                            onClick = { 
                                show2faDisable = !show2faDisable 
                                if (!show2faDisable) {
                                    disablePassword = ""
                                    disableCode = ""
                                }
                            },
                            label = if (show2faDisable) "cancel" else "disable",
                            isSuccess = isSuccessState["2fa"] == true,
                            baseColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.1f),
                            contentColor = Color.Red,
                            successColor = Color.Red
                        )
                    }
                }

                if (show2faSetup && !is2faEnabled) {
                    Spacer(Modifier.height(16.dp))
                    if (totpQr == null) {
                        OutlinedTextField(
                            value = setupPassword,
                            onValueChange = { setupPassword = it },
                            label = { Text("confirm password to setup") },
                            visualTransformation = PasswordVisualTransformation(),
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(8.dp)
                        )
                        Spacer(Modifier.height(8.dp))
                        Button(
                            onClick = { viewModel.fetchTotpQr(setupPassword) },
                            enabled = setupPassword.isNotBlank(),
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("get qr code")
                        }
                    } else {
                        TwoFactorSetup(
                            qrCodeBase64 = totpQr?.qr_code,
                            error = totpError,
                            onConfirm = { viewModel.confirmTotp(it) }
                        )
                    }
                }

                if (show2faDisable && is2faEnabled) {
                    Spacer(Modifier.height(16.dp))
                    OutlinedTextField(
                        value = disablePassword,
                        onValueChange = { disablePassword = it },
                        label = { Text("password") },
                        visualTransformation = PasswordVisualTransformation(),
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(8.dp)
                    )
                    Spacer(Modifier.height(8.dp))
                    OutlinedTextField(
                        value = disableCode,
                        onValueChange = { if (it.length <= 6) disableCode = it },
                        label = { Text("2fa code") },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(8.dp),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                    )
                    Spacer(Modifier.height(8.dp))
                    SuccessButton(
                        onClick = { viewModel.disableTotp(disablePassword, disableCode) },
                        label = "confirm disable",
                        isSuccess = isSuccessState["2fa"] == true,
                        baseColor = Color.Red,
                        enabled = disablePassword.isNotBlank() && disableCode.length == 6,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
                
                if (totpError != null && !show2faSetup && !show2faDisable) {
                     Text(totpError!!.lowercase(), color = Color.Red, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(top = 8.dp))
                }
            }

            SettingsSection(title = "invite") {
                var inviteName by remember { mutableStateOf("") }
                var maxUses by remember { mutableStateOf("1") }
                val clipboardManager = LocalClipboardManager.current
                
                var showDatePicker by remember { mutableStateOf(false) }
                val datePickerState = rememberDatePickerState(
                    initialSelectedDateMillis = System.currentTimeMillis() + 7.days.inWholeMilliseconds
                )

                Text("create invite token", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 8.dp))
                
                OutlinedTextField(
                    value = inviteName,
                    onValueChange = { inviteName = it },
                    label = { Text("name") },
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(8.dp)
                )
                Spacer(Modifier.height(8.dp))
                OutlinedTextField(
                    value = maxUses,
                    onValueChange = { if (it.all { c -> c.isDigit() }) maxUses = it },
                    label = { Text("max uses") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(8.dp)
                )
                
                Spacer(Modifier.height(8.dp))
                
                OutlinedTextField(
                    value = datePickerState.selectedDateMillis?.let { Instant.fromEpochMilliseconds(it).toString().substringBefore("T") } ?: "",
                    onValueChange = {},
                    label = { Text("expiry date") },
                    readOnly = true,
                    trailingIcon = {
                        IconButton(onClick = { showDatePicker = true }) {
                            Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Select Date")
                        }
                    },
                    modifier = Modifier.fillMaxWidth().clickable { showDatePicker = true },
                    shape = RoundedCornerShape(8.dp)
                )
                
                if (showDatePicker) {
                    DatePickerDialog(
                        onDismissRequest = { showDatePicker = false },
                        confirmButton = {
                            TextButton(onClick = { showDatePicker = false }) {
                                Text("ok")
                            }
                        }
                    ) {
                        DatePicker(state = datePickerState)
                    }
                }
                
                Spacer(Modifier.height(12.dp))
                
                SuccessButton(
                    onClick = { 
                        val nowMs = System.currentTimeMillis()
                        val expiryMs = datePickerState.selectedDateMillis ?: (nowMs + 7.days.inWholeMilliseconds)
                        viewModel.createInvite(
                            InviteRequest(
                                name = inviteName,
                                max_uses = maxUses.toIntOrNull() ?: 1,
                                start_date = Instant.fromEpochMilliseconds(nowMs),
                                expiry_date = Instant.fromEpochMilliseconds(expiryMs)
                            )
                        )
                    },
                    label = "generate invite",
                    isSuccess = isSuccessState["invite"] == true,
                    enabled = inviteName.isNotBlank(),
                    modifier = Modifier.fillMaxWidth()
                )

                if (lastInviteCode != null) {
                    Spacer(Modifier.height(16.dp))
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), RoundedCornerShape(8.dp))
                            .padding(12.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = lastInviteCode!!,
                            style = MaterialTheme.typography.bodyLarge,
                            modifier = Modifier.weight(1f)
                        )
                        IconButton(onClick = { 
                            clipboardManager.setText(AnnotatedString(lastInviteCode!!))
                        }) {
                            Icon(Icons.Default.ContentCopy, contentDescription = "Copy", modifier = Modifier.size(20.dp))
                        }
                    }
                }
            }

            SettingsSection(title = "session") {
                Button(
                    onClick = onLogout,
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(8.dp),
                    colors = ButtonDefaults.buttonColors(containerColor = Color.White, contentColor = Color.Black)
                ) {
                    Text("logout")
                }
            }

            SettingsSection(title = "danger zone", color = Color.Red.copy(alpha = 0.7f)) {
                var deletePassword by remember { mutableStateOf("") }
                var deleteTotp by remember { mutableStateOf("") }
                var showDeleteConfirm by remember { mutableStateOf(false) }

                if (!showDeleteConfirm) {
                    Button(
                        onClick = { showDeleteConfirm = true },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(8.dp),
                        colors = ButtonDefaults.buttonColors(containerColor = Color.Red.copy(alpha = 0.1f), contentColor = Color.Red)
                    ) {
                        Text("delete account")
                    }
                } else {
                    Text("confirm account deletion", color = Color.Red, style = MaterialTheme.typography.bodyMedium)
                    Spacer(Modifier.height(8.dp))
                    OutlinedTextField(
                        value = deletePassword,
                        onValueChange = { deletePassword = it },
                        label = { Text("password") },
                        visualTransformation = PasswordVisualTransformation(),
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(8.dp)
                    )
                    if (is2faEnabled) {
                        Spacer(Modifier.height(8.dp))
                        OutlinedTextField(
                            value = deleteTotp,
                            onValueChange = { if (it.length <= 6) deleteTotp = it },
                            label = { Text("2fa code") },
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(8.dp),
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                        )
                    }
                    Spacer(Modifier.height(12.dp))
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        Button(
                            onClick = { showDeleteConfirm = false },
                            modifier = Modifier.weight(1f),
                            shape = RoundedCornerShape(8.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
                        ) {
                            Text("cancel")
                        }
                        SuccessButton(
                            onClick = { viewModel.deleteAccount(
                                deletePassword, deleteTotp.ifBlank { null },
                                onLogout
                            ) },
                            label = "delete forever",
                            isSuccess = isSuccessState["delete"] == true,
                            baseColor = Color.Red.copy(alpha = 0.1f),
                            contentColor = Color.Red,
                            successColor = Color.Red,
                            modifier = Modifier.weight(1f),
                            enabled = deletePassword.isNotEmpty() && (!is2faEnabled || deleteTotp.length == 6)
                        )
                    }
                }
            }

            if (settingsError != null) {
                Text(settingsError!!, color = Color.Red, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(top = 8.dp))
            }
        }
    }
}

@Composable
fun SettingsSection(
    title: String, 
    color: Color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
    content: @Composable () -> Unit
) {
    var expanded by remember { mutableStateOf(true) }
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f), RoundedCornerShape(12.dp))
            .clip(RoundedCornerShape(12.dp))
            .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.5f))
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded = !expanded }
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(title.lowercase(), style = MaterialTheme.typography.labelSmall, color = color)
            Icon(
                if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                contentDescription = null,
                tint = color,
                modifier = Modifier.size(16.dp)
            )
        }
        
        AnimatedVisibility(visible = expanded) {
            Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp).padding(bottom = 8.dp)) {
                content()
            }
        }
    }
}

@Composable
fun SettingsField(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    buttonLabel: String,
    isSuccess: Boolean,
    onClick: () -> Unit
) {
    Column {
        OutlinedTextField(
            value = value,
            onValueChange = onValueChange,
            label = { Text(label) },
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(8.dp),
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = if (isSuccess) Color.Green else MaterialTheme.colorScheme.primary
            )
        )
        Spacer(Modifier.height(8.dp))
        SuccessButton(
            onClick = onClick,
            label = buttonLabel,
            isSuccess = isSuccess,
            enabled = value.isNotBlank(),
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Composable
fun SuccessButton(
    onClick: () -> Unit,
    label: String,
    isSuccess: Boolean,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    baseColor: Color = MaterialTheme.colorScheme.primary,
    contentColor: Color = MaterialTheme.colorScheme.onPrimary,
    successColor: Color = Color.Green.copy(alpha = 0.8f)
) {
    val backgroundColor by animateColorAsState(
        targetValue = if (isSuccess) successColor else baseColor,
        animationSpec = tween(500)
    )

    Button(
        onClick = onClick,
        modifier = modifier,
        enabled = enabled,
        shape = RoundedCornerShape(8.dp),
        colors = ButtonDefaults.buttonColors(
            containerColor = backgroundColor,
            contentColor = if (isSuccess) Color.White else contentColor
        )
    ) {
        Text(if (isSuccess) "success" else label)
    }
}

@OptIn(ExperimentalTime::class)
@Composable
fun TwoFactorSetup(
    qrCodeBase64: String?,
    error: String?,
    onConfirm: (String) -> Unit
) {
    var code by remember { mutableStateOf("") }
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(12.dp))
            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.1f), RoundedCornerShape(12.dp))
            .padding(20.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        if (qrCodeBase64 != null) {
            val bitmap = remember(qrCodeBase64) {
                val base64Data = qrCodeBase64.substringAfter("base64,")
                val decodedString = Base64.decode(base64Data, Base64.DEFAULT)
                BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
            }
            
            bitmap?.let {
                Image(
                    bitmap = it.asImageBitmap(),
                    contentDescription = "QR Code",
                    modifier = Modifier
                        .size(180.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color.White)
                        .padding(8.dp)
                )
            }
        } else {
            CircularProgressIndicator(modifier = Modifier.size(40.dp))
        }
        
        Spacer(Modifier.height(24.dp))
        
        OutlinedTextField(
            value = code,
            onValueChange = { if (it.length <= 6) code = it },
            placeholder = { Text("000000") },
            modifier = Modifier.width(150.dp),
            textStyle = MaterialTheme.typography.headlineMedium.copy(textAlign = TextAlign.Center),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            shape = RoundedCornerShape(8.dp)
        )

        if (error != null) {
            Text(error.lowercase(), color = Color.Red, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(top = 8.dp))
        }
        
        Spacer(Modifier.height(16.dp))
        SuccessButton(
            onClick = { onConfirm(code) },
            label = "verify and enable",
            isSuccess = false, // Managed by parent
            enabled = code.length == 6,
            modifier = Modifier.fillMaxWidth()
        )
    }
}
