package com.a2i.forwarder.ui.screens

import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
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.graphics.ImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.store.RuleMode
import com.a2i.forwarder.ui.IconBox
import com.a2i.forwarder.ui.ScreenTitle
import com.a2i.forwarder.ui.SectionCard
import com.a2i.forwarder.ui.StatusBadge
import com.a2i.forwarder.ui.SwitchRow
import com.a2i.forwarder.ui.drawableToImageBitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

private data class AppInfo(val pkg: String, val label: String, val icon: ImageBitmap?, val system: Boolean)

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun AppManageScreen() {
    val context = LocalContext.current
    val app = A2iApp.instance
    val mode by app.appRules.mode.collectAsState()
    val blacklist by app.appRules.blacklist.collectAsState()
    val whitelist by app.appRules.whitelist.collectAsState()
    var showSystem by remember { mutableStateOf(false) }
    var query by remember { mutableStateOf("") }
    var apps by remember { mutableStateOf<List<AppInfo>>(emptyList()) }
    var loading by remember { mutableStateOf(true) }

    LaunchedEffect(Unit) {
        loading = true
        apps = loadApps(context)
        loading = false
    }

    val visible = apps.filter {
        (showSystem || !it.system) &&
            (query.isBlank() || it.label.contains(query, true) || it.pkg.contains(query, true))
    }

    LazyColumn(
        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        item { ScreenTitle("应用转发", "按应用控制通知是否进入转发链路") }

        item {
            SectionCard("规则模式", subtitle = "黑名单适合默认转发；白名单适合只转发少数 App") {
                FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    FilterChip(
                        selected = mode == RuleMode.BLACKLIST,
                        onClick = { app.appScope.launch { app.appRules.setMode(RuleMode.BLACKLIST) } },
                        label = { Text("黑名单模式") },
                        leadingIcon = { Icon(Icons.Filled.Tune, null, modifier = Modifier.size(18.dp)) },
                    )
                    FilterChip(
                        selected = mode == RuleMode.WHITELIST,
                        onClick = { app.appScope.launch { app.appRules.setMode(RuleMode.WHITELIST) } },
                        label = { Text("白名单模式") },
                        leadingIcon = { Icon(Icons.Outlined.Apps, null, modifier = Modifier.size(18.dp)) },
                    )
                }
                SwitchRow(
                    title = "显示系统应用",
                    subtitle = if (showSystem) "列表包含系统服务和预装组件" else "当前只显示用户安装的应用",
                    checked = showSystem,
                    icon = Icons.Outlined.Apps,
                    tint = MaterialTheme.colorScheme.secondary,
                ) { showSystem = it }
            }
        }

        item {
            OutlinedTextField(
                value = query,
                onValueChange = { query = it },
                label = { Text("搜索应用或包名") },
                leadingIcon = { Icon(Icons.Filled.Search, null) },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true,
            )
        }

        item {
            Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                Text(
                    if (loading) "正在读取应用列表" else "显示 ${visible.size} / ${apps.size} 个应用",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.weight(1f),
                )
                StatusBadge(
                    text = if (mode == RuleMode.BLACKLIST) "默认转发" else "仅白名单",
                    tint = MaterialTheme.colorScheme.primary,
                )
            }
        }

        if (loading) {
            item {
                Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
            }
        } else {
            items(visible, key = { it.pkg }) { ai ->
                val on = when (mode) {
                    RuleMode.BLACKLIST -> ai.pkg !in blacklist
                    RuleMode.WHITELIST -> ai.pkg in whitelist
                }
                AppRow(ai, on) { v -> app.appScope.launch { app.appRules.setForwarding(ai.pkg, v) } }
            }
        }
    }
}

@Composable
private fun AppRow(ai: AppInfo, on: Boolean, onChange: (Boolean) -> Unit) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        color = MaterialTheme.colorScheme.surface,
        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
    ) {
        Row(
            Modifier.fillMaxWidth().padding(12.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (ai.icon != null) {
                Image(bitmap = ai.icon, contentDescription = null, modifier = Modifier.size(42.dp))
            } else {
                IconBox(icon = Icons.Outlined.Apps, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(42.dp))
            }
            Spacer(Modifier.width(12.dp))
            Column(Modifier.weight(1f)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        ai.label,
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Medium,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f),
                    )
                    if (ai.system) {
                        Spacer(Modifier.width(8.dp))
                        StatusBadge("系统", MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                }
                Text(
                    ai.pkg,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
            Spacer(Modifier.width(12.dp))
            Switch(checked = on, onCheckedChange = onChange)
        }
    }
}

private suspend fun loadApps(context: Context): List<AppInfo> = withContext(Dispatchers.IO) {
    val pm = context.packageManager
    pm.getInstalledApplications(PackageManager.GET_META_DATA)
        .map {
            AppInfo(
                pkg = it.packageName,
                label = pm.getApplicationLabel(it).toString(),
                icon = runCatching { drawableToImageBitmap(pm.getApplicationIcon(it)) }.getOrNull(),
                system = it.flags and ApplicationInfo.FLAG_SYSTEM != 0,
            )
        }
        .sortedBy { it.label.lowercase() }
}