package com.a2i.forwarder.ui.screens

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.FilterAlt
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.core.AdFilter
import com.a2i.forwarder.ui.ScreenTitle
import com.a2i.forwarder.ui.SectionCard
import com.a2i.forwarder.ui.SwitchRow
import kotlinx.coroutines.launch

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun FilterScreen() {
    val app = A2iApp.instance
    val adOn by app.settings.adFilterEnabled.collectAsState()
    val codeOn by app.settings.codeEnabled.collectAsState()
    val specialOn by app.settings.specialEnabled.collectAsState()
    val skipOngoing by app.settings.skipOngoing.collectAsState()
    val customKw by app.settings.adKeywords.collectAsState()
    var newKw by remember { mutableStateOf("") }

    LazyColumn(
        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        item { ScreenTitle("过滤与优化", "减少噪音，保留真正需要同步到 iOS 的通知") }

        item {
            SectionCard("功能开关", subtitle = "规则按通知处理流水线顺序执行") {
                SwitchRow(
                    title = "广告过滤",
                    subtitle = "命中营销关键词的通知将被丢弃",
                    checked = adOn,
                    icon = Icons.Outlined.FilterAlt,
                    tint = MaterialTheme.colorScheme.primary,
                ) { app.appScope.launch { app.settings.setAdFilter(it) } }
                SwitchRow(
                    title = "验证码自动提取",
                    subtitle = "自动提取验证码，收到即复制并可点击复制",
                    checked = codeOn,
                    icon = Icons.Filled.Notifications,
                    tint = MaterialTheme.colorScheme.secondary,
                ) { app.appScope.launch { app.settings.setCode(it) } }
                SwitchRow(
                    title = "微信 / QQ / Telegram 优化",
                    subtitle = "发送者作标题、按会话分组、重要通知提级",
                    checked = specialOn,
                    icon = Icons.Outlined.Apps,
                    tint = MaterialTheme.colorScheme.tertiary,
                ) { app.appScope.launch { app.settings.setSpecial(it) } }
                SwitchRow(
                    title = "过滤持续性通知",
                    subtitle = "跳过音乐、下载、通话等 ongoing 通知",
                    checked = skipOngoing,
                    icon = Icons.Filled.Settings,
                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                ) { app.appScope.launch { app.settings.setSkipOngoing(it) } }
            }
        }

        item {
            SectionCard("内置广告关键词", subtitle = "系统预置规则不可编辑") {
                FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
                    AdFilter.DEFAULT_KEYWORDS.forEach { kw ->
                        AssistChip(onClick = {}, label = { Text(kw) })
                    }
                }
            }
        }

        item {
            SectionCard("自定义关键词", subtitle = "命中任意关键词的通知会被广告过滤拦截") {
                if (customKw.isEmpty()) {
                    EmptyKeywordState()
                } else {
                    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        customKw.forEach { kw ->
                            KeywordRow(kw) {
                                app.appScope.launch { app.settings.setAdKeywords(customKw - kw) }
                            }
                        }
                    }
                }
                Spacer(Modifier.size(12.dp))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    OutlinedTextField(
                        value = newKw,
                        onValueChange = { newKw = it },
                        label = { Text("添加关键词") },
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                    )
                    Spacer(Modifier.width(8.dp))
                    Button(onClick = {
                        val t = newKw.trim()
                        if (t.isNotEmpty() && t !in customKw) {
                            app.appScope.launch { app.settings.setAdKeywords(customKw + t) }
                            newKw = ""
                        }
                    }) {
                        Icon(Icons.Filled.Add, null, modifier = Modifier.size(18.dp))
                        Spacer(Modifier.width(6.dp))
                        Text("添加")
                    }
                }
            }
        }
    }
}

@Composable
private fun EmptyKeywordState() {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
    ) {
        Text(
            "暂无自定义关键词",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(12.dp),
        )
    }
}

@Composable
private fun KeywordRow(keyword: String, onDelete: () -> Unit) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
    ) {
        Row(Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(keyword, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
            IconButton(onClick = onDelete) { Icon(Icons.Filled.Close, "删除") }
        }
    }
}