package chat.vojo.proxy.ui

import androidx.compose.foundation.background
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
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.selection.toggleable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
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.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import chat.vojo.proxy.core.AppSettings
import chat.vojo.proxy.ui.theme.Vojo

/** Loose but useful: enough to keep garbage out of VpnService.addDnsServer. */
private fun isValidIp(s: String): Boolean {
    if (s.isBlank()) return false
    return if (':' in s) {
        s.matches(Regex("^[0-9a-fA-F:]{2,45}$")) && s.count { it == ':' } in 1..8
    } else {
        val parts = s.split('.')
        parts.size == 4 && parts.all { p -> p.toIntOrNull()?.let { it in 0..255 } == true && p.length <= 3 }
    }
}

@Composable
fun SettingsScreen(
    settings: AppSettings,
    onChange: ((AppSettings) -> AppSettings) -> Unit,
) {
    var dnsEdit by rememberSaveable { mutableStateOf<String?>(null) }
    var mtuEdit by rememberSaveable { mutableStateOf<String?>(null) }

    val dnsValue = dnsEdit ?: settings.dns
    val mtuValue = mtuEdit ?: settings.mtu.toString()
    val dnsError = if (dnsEdit != null && !isValidIp(dnsValue.trim())) "Не похоже на IP-адрес — не сохранено" else null
    val mtuError = if (mtuEdit != null && (mtuValue.toIntOrNull() == null || mtuValue.toInt() !in 1000..9000)) "Допустимо 1000–9000 — не сохранено" else null

    Column(
        // imePadding so the keyboard never covers the DNS/MTU fields under
        // edge-to-edge (the window isn't resized when decor fits system windows).
        Modifier.fillMaxSize().verticalScroll(rememberScrollState()).imePadding().padding(18.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        SectionLabel("Сеть")

        VojoTextField(
            value = dnsValue,
            onValueChange = {
                dnsEdit = it
                val v = it.trim()
                if (isValidIp(v)) onChange { s -> s.copy(dns = v) }
            },
            label = "DNS-сервер",
            placeholder = "1.1.1.1",
            mono = true,
            keyboardType = KeyboardType.Ascii,
            error = dnsError,
        )
        Text("DNS-запросы идут через туннель — провайдер их не видит.", color = Vojo.faint, fontSize = 12.sp)

        VojoTextField(
            value = mtuValue,
            onValueChange = {
                val v = it.filter(Char::isDigit).take(4)
                mtuEdit = v
                v.toIntOrNull()?.let { n -> if (n in 1000..9000) onChange { s -> s.copy(mtu = n) } }
            },
            label = "MTU",
            placeholder = "8500",
            mono = true,
            keyboardType = KeyboardType.Number,
            error = mtuError,
        )

        ToggleRow(
            title = "IPv6",
            subtitle = "Маршрутизировать IPv6-трафик через туннель",
            checked = settings.ipv6,
            onToggle = { onChange { s -> s.copy(ipv6 = it) } },
        )

        Text(
            "Изменения применяются при следующем подключении.",
            color = Vojo.faint, fontSize = 12.sp,
        )
    }
}

@Composable
private fun ToggleRow(title: String, subtitle: String, checked: Boolean, onToggle: (Boolean) -> Unit) {
    PanelCard(Modifier.fillMaxWidth()) {
        Row(
            Modifier
                .toggleable(value = checked, role = Role.Switch) { onToggle(it) }
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(Modifier.weight(1f)) {
                Text(title, color = Vojo.text, fontSize = 15.sp, fontWeight = FontWeight.Medium)
                Text(subtitle, color = Vojo.muted, fontSize = 12.5.sp)
            }
            Switch(checked)
        }
    }
}

@Composable
private fun Switch(checked: Boolean) {
    Box(
        Modifier
            .width(46.dp)
            .height(26.dp)
            .clip(RoundedCornerShape(13.dp))
            .background(if (checked) Vojo.fleet else Vojo.surface2)
            .padding(3.dp),
        contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart,
    ) {
        Box(Modifier.size(20.dp).clip(RoundedCornerShape(10.dp)).background(Color.White))
    }
}
