package com.a2i.forwarder.ui.screens

import android.content.Intent
import android.provider.Settings
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.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.CheckCircle
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.PowerSettingsNew
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.ui.ClickRow
import com.a2i.forwarder.ui.IconBox
import com.a2i.forwarder.ui.MetricBlock
import com.a2i.forwarder.ui.SectionCard
import com.a2i.forwarder.ui.StatusBadge
import com.a2i.forwarder.ui.SwitchRow
import com.a2i.forwarder.ui.appVersionName
import com.a2i.forwarder.ui.isNotificationListenerEnabled
import kotlinx.coroutines.launch

@Composable
fun HomeScreen(onOpenLog: () -> Unit, onOpenSettings: () -> Unit) {
    val context = LocalContext.current
    val app = A2iApp.instance
    val forwarding by app.settings.forwardingEnabled.collectAsState()
    val current by app.settings.currentServer.collectAsState()
    val sent by app.logStore.sentCount.collectAsState()
    val filtered by app.logStore.filteredCount.collectAsState()
    val failed by app.logStore.failedCount.collectAsState()
    val smsSuspended by app.settings.smsSuspended.collectAsState()
    val update by app.updateChecker.updateInfo.collectAsState()
    var showUpdateDialog by remember { mutableStateOf(false) }

    var granted by remember { mutableStateOf(isNotificationListenerEnabled(context)) }
    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(lifecycleOwner) {
        val obs = LifecycleEventObserver { _, e ->
            if (e == Lifecycle.Event.ON_RESUME) granted = isNotificationListenerEnabled(context)
        }
        lifecycleOwner.lifecycle.addObserver(obs)
        onDispose { lifecycleOwner.lifecycle.removeObserver(obs) }
    }

    LazyColumn(
        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        item {
            HomeHero(
                granted = granted,
                forwarding = forwarding,
                version = appVersionName(context),
                modifier = Modifier.padding(top = 16.dp),
            )
        }

        val info = update
        if (info != null) {
            item {
                SectionCard {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        IconBox(icon = Icons.Filled.SystemUpdate, tint = MaterialTheme.colorScheme.primary)
                        Spacer(Modifier.width(12.dp))
                        Column(Modifier.weight(1f)) {
                            Text("发现新版本 v${info.latestVersion}", style = MaterialTheme.typography.titleMedium)
                            Text(
                                "安装包 ${formatSize(info.apkSize)} · 点击立即更新",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                            )
                        }
                        StatusBadge(text = "新", tint = MaterialTheme.colorScheme.primary)
                    }
                    Spacer(Modifier.size(12.dp))
                    Button(onClick = { showUpdateDialog = true }, modifier = Modifier.fillMaxWidth()) { Text("立即更新") }
                }
            }
        }

        if (smsSuspended) {
            item {
                SectionCard {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        IconBox(
                            icon = Icons.Filled.WarningAmber,
                            tint = MaterialTheme.colorScheme.error,
                        )
                        Spacer(Modifier.width(12.dp))
                        Column(Modifier.weight(1f)) {
                            Text("短信兜底已停用", style = MaterialTheme.typography.titleMedium)
                            Text(
                                "短信余额不足，断网转发已关闭。请在「设置 → 断网短信兜底」补充额度",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                            )
                        }
                    }
                }
            }
        }

        item {
            SectionCard {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    IconBox(
                        icon = if (granted) Icons.Filled.CheckCircle else Icons.Filled.WarningAmber,
                        tint = if (granted) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.error,
                    )
                    Spacer(Modifier.width(12.dp))
                    Column(Modifier.weight(1f)) {
                        Text(if (granted) "通知监听已开启" else "需要授权通知监听", style = MaterialTheme.typography.titleMedium)
                        Text(
                            if (granted) "系统通知将按规则处理并推送到 Bark" else "授权后才能读取 Android 通知并转发",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                    StatusBadge(
                        text = if (granted) "已授权" else "未授权",
                        tint = if (granted) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.error,
                    )
                }
                if (!granted) {
                    Spacer(Modifier.size(12.dp))
                    Button(
                        onClick = { context.startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)) },
                        modifier = Modifier.fillMaxWidth(),
                    ) { Text("前往系统授权") }
                }
            }
        }

        item {
            SectionCard("运行状态", subtitle = "转发能力、目标服务器和日志入口") {
                SwitchRow(
                    title = "通知转发",
                    subtitle = if (forwarding) "新通知会继续转发到 Bark" else "当前已暂停所有转发",
                    checked = forwarding,
                    icon = Icons.Filled.PowerSettingsNew,
                    tint = if (forwarding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                ) { v ->
                    app.appScope.launch { app.settings.setForwarding(v) }
                }
                ClickRow(
                    title = current?.name?.ifBlank { "未命名服务器" } ?: "未配置 Bark 服务器",
                    subtitle = current?.server ?: "进入设置添加官方或自建 Bark 服务",
                    icon = Icons.Filled.Settings,
                    tint = MaterialTheme.colorScheme.secondary,
                    onClick = onOpenSettings,
                )
                if (current?.deviceKey.isNullOrBlank()) {
                    Text(
                        "当前服务器未填写 device key",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error,
                        modifier = Modifier.padding(start = 50.dp),
                    )
                }
                ClickRow(
                    title = "查看转发日志",
                    subtitle = "最近 300 条处理记录",
                    icon = Icons.Filled.History,
                    tint = MaterialTheme.colorScheme.primary,
                    onClick = onOpenLog,
                )
            }
        }

        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                MetricBlock("已转发", sent.toString(), MaterialTheme.colorScheme.primary, Modifier.weight(1f))
                MetricBlock("已过滤", filtered.toString(), MaterialTheme.colorScheme.secondary, Modifier.weight(1f))
                MetricBlock("失败", failed.toString(), MaterialTheme.colorScheme.error, Modifier.weight(1f))
            }
        }

        item {
            Text(
                "v${appVersionName(context)}",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.fillMaxWidth().padding(top = 2.dp, bottom = 18.dp),
                textAlign = TextAlign.Center,
            )
        }
    }

    if (showUpdateDialog) {
        val info = update
        if (info != null) UpdateDialog(info, onDismiss = { showUpdateDialog = false })
    }
}

@Composable
private fun HomeHero(
    granted: Boolean,
    forwarding: Boolean,
    version: String,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier
            .fillMaxWidth()
            .background(
                brush = Brush.linearGradient(
                    colors = listOf(MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.secondary),
                ),
                shape = RoundedCornerShape(12.dp),
            )
            .padding(18.dp),
    ) {
        Column {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Box(
                    modifier = Modifier
                        .size(44.dp)
                        .background(Color.White.copy(alpha = 0.18f), RoundedCornerShape(8.dp)),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(Icons.Filled.Notifications, null, tint = Color.White, modifier = Modifier.size(24.dp))
                }
                Spacer(Modifier.width(12.dp))
                Column(Modifier.weight(1f)) {
                    Text("a2i", style = MaterialTheme.typography.displaySmall, color = Color.White)
                    Text("安卓通知转发到 iOS Bark", style = MaterialTheme.typography.bodyMedium, color = Color.White.copy(alpha = 0.82f))
                }
                StatusBadge(
                    text = if (granted && forwarding) "运行中" else "待处理",
                    tint = Color.White,
                )
            }
            Spacer(Modifier.size(14.dp))
            Text(
                if (granted && forwarding) "监听、过滤、提取验证码和推送链路已就绪。" else "完成授权并开启转发后，通知会按规则推送到 iOS。",
                style = MaterialTheme.typography.bodyMedium,
                color = Color.White.copy(alpha = 0.86f),
            )
            Text(
                "Build $version",
                style = MaterialTheme.typography.bodySmall,
                color = Color.White.copy(alpha = 0.68f),
                modifier = Modifier.padding(top = 8.dp),
            )
        }
    }
}