package com.jihe.punchnet.screen

import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.jihe.punchnet.data.RouteItem
import com.jihe.punchnet.data.RouteViewModel
import com.jihe.punchnet.helper.IntToIPString
import com.jihe.punchnet.helper.parseCIDRAndGW
import com.jihe.punchnet.sdlan.network.maskIPToDigit
import com.jihe.punchnet.data.NodeRepository
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.rememberScrollState

@Composable
fun SettingsScreen(enabled: Boolean, routeViewModel: RouteViewModel) {
    val localProfile by NodeRepository.localProfile.collectAsState()
    val exitNodes by NodeRepository.exitNodes.collectAsState()
    val routeItems by routeViewModel.allRoutes.collectAsState(initial = emptyList())
    
    val showAddRoute = remember { mutableStateOf<RouteItem?>(null) }
    val shouldShow = remember { mutableStateOf(false) }

    AddOrModifyRouteDialog(routeViewModel, showAddRoute, shouldShow, exitNodes)

    LazyColumn(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        // Section 1: Local Profile
        item {
            Text("本机信息", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
            Spacer(modifier = Modifier.height(8.dp))
            if (localProfile != null) {
                Card(modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text("Hostname: ${localProfile!!.hostname}")
                        Text("IP: ${localProfile!!.ip}/${localProfile!!.maskLen}")
                        Text("Identity ID: ${localProfile!!.identityId}")
                    }
                }
            } else {
                Text("暂无本机网络信息", color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 16.dp))
            }
        }

        // Section 2: Exit Nodes
        item {
            Text("出口节点", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
            Spacer(modifier = Modifier.height(8.dp))
            if (exitNodes.isEmpty()) {
                Text("当前网络无可用出口节点", color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 16.dp))
            }
        }
        items(exitNodes) { exitNode ->
            Card(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text("名称: ${exitNode.nodeName}", fontWeight = FontWeight.Bold)
                    Text("网关 IP: ${exitNode.gateway}")
                    Text("代理网段: ${exitNode.targetNetwork}")
                }
            }
        }
        item { Spacer(modifier = Modifier.height(8.dp)) }

        // Section 3: Routes
        item {
            Text("本地路由配置", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
            Spacer(modifier = Modifier.height(8.dp))
        }
        items(routeItems) { item ->
            RouteCard(routeViewModel, item, enabled)
        }
        item {
            Spacer(modifier = Modifier.height(8.dp))
            Button(
                enabled = enabled,
                onClick = { shouldShow.value = true },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("添加路由")
            }
        }
    }
}

@Composable
fun AddOrModifyRouteDialog(
    routeViewModel: RouteViewModel,
    initRoute: MutableState<RouteItem?>,
    shouldShowRoute: MutableState<Boolean>,
    exitNodes: List<com.jihe.punchnet.api.ExitNodeItem>
) {
    if (shouldShowRoute.value) {
        val context = LocalContext.current
        var cidr by remember { mutableStateOf("") }
        var gw by remember { mutableStateOf("") }

        AlertDialog(
            onDismissRequest = { shouldShowRoute.value = false },
            confirmButton = {
                Button(
                    onClick = {
                        val item = parseCIDRAndGW(cidr, gw)
                        if (item == null) {
                            Toast.makeText(context, "数据解析出错", Toast.LENGTH_SHORT).show()
                        } else {
                            routeViewModel.insert(item)
                            shouldShowRoute.value = false
                        }
                    }
                ) {
                    Text("确定")
                }
            },
            title = { Text("添加新路由") },
            text = {
                Column {
                    TextField(
                        value = cidr,
                        onValueChange = { cidr = it },
                        label = { Text("CIDR") },
                        placeholder = { Text("例如 0.0.0.0/0") }
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    TextField(
                        value = gw,
                        onValueChange = { gw = it },
                        label = { Text("Gateway") },
                        placeholder = { Text("例如 10.10.4.5") }
                    )
                    if (exitNodes.isNotEmpty()) {
                        Spacer(modifier = Modifier.height(8.dp))
                        Text("快捷选择出口节点网关:", fontSize = 12.sp)
                        Row(
                            modifier = Modifier.horizontalScroll(rememberScrollState()),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            exitNodes.forEach { en ->
                                SuggestionChip(
                                    onClick = { 
                                        gw = en.gateway 
                                        if (cidr.isEmpty()) cidr = en.targetNetwork
                                    },
                                    label = { Text(en.nodeName) }
                                )
                            }
                        }
                    }
                }
            }
        )
    }
}

@Composable
fun RouteCard(
    routeViewModel: RouteViewModel,
    item: RouteItem,
    enabled: Boolean,
) {
    Card(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.height(48.dp).padding(horizontal = 16.dp)
        ) {
            Icon(
                Icons.Default.Clear,
                contentDescription = "delete route",
                modifier = Modifier.size(24.dp).clickable(enabled = enabled) {
                    routeViewModel.deleteById(item.id)
                }
            )
            Spacer(modifier = Modifier.width(16.dp))
            Text("${IntToIPString(item.net_ip)}/${maskIPToDigit(item.mask_ip)}")
            Spacer(modifier = Modifier.width(16.dp))
            Text("-> ${IntToIPString(item.gateway)}")
        }
    }
}
