package dev.kaizen.app.settings

import androidx.biometric.BiometricManager
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.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
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.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
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.unit.dp
import androidx.compose.ui.unit.sp
import dev.kaizen.app.R
import dev.kaizen.app.net.AppDevice
import dev.kaizen.app.net.ServerConfig
import dev.kaizen.app.ui.shape.KaizenShapes
import dev.kaizen.app.ui.theme.KaizenSemanticColors
import dev.kaizen.app.ui.theme.LocalKaizenAccent
import dev.kaizen.app.ui.icon.KaizenIcons

@Composable
fun SecuritySection(
    viewModel: SettingsViewModel,
    config: ServerConfig?,
) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val context = LocalContext.current

    val biometricEnabled by viewModel.biometricEnabled.collectAsState()
    val devices by viewModel.devices.collectAsState()
    val devicesLoading by viewModel.devicesLoading.collectAsState()
    val passwordResult by viewModel.passwordChangeResult.collectAsState()

    val biometricAvailable = remember {
        val bm = BiometricManager.from(context)
        bm.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
    }

    val biometricNotEnrolled = remember {
        val bm = BiometricManager.from(context)
        bm.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED
    }

    LaunchedEffect(config) {
        config?.let { viewModel.loadDevices(it) }
    }

    Text(
        stringResource(R.string.settings_section_security),
        color = cs.onSurfaceVariant.copy(alpha = 0.6f),
        fontSize = 12.sp,
        fontWeight = FontWeight.Bold,
        modifier = Modifier.padding(start = 8.dp, bottom = 8.dp),
    )

    // Biometric toggle
    SettingsCard(modifier = Modifier.padding(bottom = 16.dp)) {
        SettingsOptionRow(
            title = stringResource(R.string.settings_biometric_title),
            description = if (biometricNotEnrolled) stringResource(R.string.settings_biometric_not_enrolled)
            else stringResource(R.string.settings_biometric_desc),
            icon = KaizenIcons.Fingerprint,
        ) {
            Switch(
                checked = biometricEnabled && biometricAvailable,
                onCheckedChange = { viewModel.setBiometricEnabled(it) },
                enabled = biometricAvailable,
                colors = SwitchDefaults.colors(
                    checkedThumbColor = accent.onPrimary,
                    checkedTrackColor = accent.primary,
                ),
            )
        }
    }

    // Devices
    SettingsCard(modifier = Modifier.padding(bottom = 16.dp)) {
        SettingsOptionRow(
            title = stringResource(R.string.settings_devices_title),
            description = stringResource(R.string.settings_devices_desc),
            icon = KaizenIcons.Smartphone,
        ) {
            if (devicesLoading) {
                CircularProgressIndicator(
                    color = accent.primary,
                    strokeWidth = 2.dp,
                    modifier = Modifier.size(20.dp),
                )
            } else {
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    devices.forEach { device ->
                        DeviceRow(
                            device = device,
                            onRevoke = { config?.let { viewModel.revokeDevice(it, device.id) } },
                        )
                    }
                    if (devices.isEmpty()) {
                        Text(
                            "–",
                            color = cs.onSurfaceVariant.copy(alpha = 0.4f),
                            fontSize = 13.sp,
                        )
                    }
                }
            }
        }
    }

    // Change password
    SettingsCard(modifier = Modifier.padding(bottom = 24.dp)) {
        SettingsOptionRow(
            title = stringResource(R.string.settings_password_title),
            description = "",
            icon = KaizenIcons.Key,
        ) {
            PasswordChangeForm(
                onSubmit = { current, new_ ->
                    config?.let { viewModel.changePassword(it, current, new_) }
                },
                result = passwordResult,
                onClearResult = { viewModel.clearPasswordResult() },
            )
        }
    }
}

@Composable
private fun DeviceRow(device: AppDevice, onRevoke: () -> Unit) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val locale = java.util.Locale.getDefault()

    val lastUsedText = remember(device.lastUsedAt) {
        if (device.lastUsedAt != null) {
            try {
                val date = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", locale).parse(device.lastUsedAt)
                    ?: java.util.Date(device.lastUsedAt.toLongOrNull() ?: 0)
                java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM, locale).format(date)
            } catch (_: Exception) {
                device.lastUsedAt
            }
        } else null
    }

    Row(
        Modifier
            .fillMaxWidth()
            .clip(KaizenShapes.md)
            .background(cs.surface.copy(alpha = 0.4f))
            .padding(12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column(Modifier.weight(1f)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    device.name.ifBlank { "App" },
                    color = cs.onBackground,
                    fontSize = 13.sp,
                    fontWeight = FontWeight.Medium,
                )
                if (device.isCurrent) {
                    Spacer(Modifier.width(6.dp))
                    Text(
                        stringResource(R.string.settings_device_current),
                        color = accent.primary,
                        fontSize = 11.sp,
                        fontWeight = FontWeight.SemiBold,
                    )
                }
            }
            Text(
                if (lastUsedText != null) stringResource(R.string.settings_device_last_used, lastUsedText)
                else stringResource(R.string.settings_device_never_used),
                color = cs.onSurfaceVariant.copy(alpha = 0.6f),
                fontSize = 11.sp,
            )
        }
        if (!device.isCurrent) {
            Text(
                stringResource(R.string.settings_device_revoke),
                color = KaizenSemanticColors.error,
                fontSize = 12.sp,
                fontWeight = FontWeight.Medium,
                modifier = Modifier
                    .clip(KaizenShapes.sm)
                    .clickable { onRevoke() }
                    .padding(horizontal = 8.dp, vertical = 4.dp),
            )
        }
    }
}

@Composable
private fun PasswordChangeForm(
    onSubmit: (currentPassword: String, newPassword: String) -> Unit,
    result: String?,
    onClearResult: () -> Unit,
) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current

    var current by remember { mutableStateOf("") }
    var new_ by remember { mutableStateOf("") }
    var confirm by remember { mutableStateOf("") }
    var localError by remember { mutableStateOf<String?>(null) }

    val mismatchMsg = stringResource(R.string.settings_password_error_mismatch)
    val shortMsg = stringResource(R.string.settings_password_error_short)
    val successMsg = stringResource(R.string.settings_password_success)
    val wrongMsg = stringResource(R.string.settings_password_error_wrong)
    val unknownMsg = stringResource(R.string.settings_password_error_unknown)

    LaunchedEffect(result) {
        when (result) {
            "ok" -> {
                current = ""; new_ = ""; confirm = ""; localError = null
                kotlinx.coroutines.delay(2000)
                onClearResult()
            }
            "invalid_password" -> { localError = wrongMsg; onClearResult() }
            "password_too_short" -> { localError = shortMsg; onClearResult() }
            null -> {}
            else -> { localError = unknownMsg; onClearResult() }
        }
    }

    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        PasswordField(value = current, onValueChange = { current = it; localError = null }, placeholder = stringResource(R.string.settings_password_current))
        PasswordField(value = new_, onValueChange = { new_ = it; localError = null }, placeholder = stringResource(R.string.settings_password_new))
        PasswordField(value = confirm, onValueChange = { confirm = it; localError = null }, placeholder = stringResource(R.string.settings_password_confirm), imeAction = ImeAction.Done, onImeDone = {
            if (new_.length >= 8 && new_ == confirm && current.isNotEmpty()) onSubmit(current, new_)
        })

        if (localError != null) {
            Text(localError!!, color = KaizenSemanticColors.error, fontSize = 12.sp)
        }
        if (result == "ok") {
            Text(successMsg, color = accent.primary, fontSize = 12.sp, fontWeight = FontWeight.Medium)
        }

        val canSubmit = current.isNotEmpty() && new_.length >= 8 && new_ == confirm
        Box(
            Modifier
                .fillMaxWidth()
                .heightIn(min = 40.dp)
                .shadow(elevation = if (canSubmit) 4.dp else 2.dp, shape = KaizenShapes.md, clip = false)
                .clip(KaizenShapes.md)
                .background(
                    if (canSubmit) Brush.linearGradient(listOf(accent.primary, accent.primaryDeep))
                    else Brush.linearGradient(listOf(cs.surface, cs.surface))
                )
                .clickable(enabled = canSubmit) {
                    if (new_ != confirm) { localError = mismatchMsg; return@clickable }
                    if (new_.length < 8) { localError = shortMsg; return@clickable }
                    onSubmit(current, new_)
                }
                .padding(vertical = 10.dp),
            contentAlignment = Alignment.Center,
        ) {
            Text(
                stringResource(R.string.settings_password_submit),
                color = if (canSubmit) accent.onPrimary else cs.onSurfaceVariant,
                fontSize = 13.sp,
                fontWeight = FontWeight.SemiBold,
            )
        }
    }
}

@Composable
private fun PasswordField(
    value: String,
    onValueChange: (String) -> Unit,
    placeholder: String,
    imeAction: ImeAction = ImeAction.Next,
    onImeDone: () -> Unit = {},
) {
    val cs = MaterialTheme.colorScheme
    val isDark = isSystemInDarkTheme()
    val accent = LocalKaizenAccent.current

    val bg = if (isDark) {
        Brush.verticalGradient(listOf(Color(0xFF1E293B).copy(alpha = 0.60f), Color(0xFF0F172A).copy(alpha = 0.72f)))
    } else {
        Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.85f), Color(0xFFEEF2F6).copy(alpha = 0.75f)))
    }
    val border = if (isDark) {
        Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.14f), Color.White.copy(alpha = 0.03f)))
    } else {
        Brush.verticalGradient(listOf(Color.White.copy(alpha = 0.50f), Color.Black.copy(alpha = 0.05f)))
    }

    Box(
        Modifier
            .fillMaxWidth()
            .clip(KaizenShapes.md)
            .background(bg)
            .border(1.dp, border, KaizenShapes.md)
            .heightIn(min = 44.dp)
            .padding(horizontal = 14.dp, vertical = 12.dp),
        contentAlignment = Alignment.CenterStart,
    ) {
        if (value.isEmpty()) {
            Text(placeholder, color = cs.onSurfaceVariant.copy(alpha = 0.5f), fontSize = 14.sp)
        }
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            textStyle = TextStyle(color = cs.onBackground, fontSize = 14.sp),
            cursorBrush = SolidColor(accent.primary),
            singleLine = true,
            visualTransformation = PasswordVisualTransformation(),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),
            keyboardActions = KeyboardActions(onDone = { onImeDone() }),
            modifier = Modifier.fillMaxWidth(),
        )
    }
}
