package com.jihe.punchnet.screen

import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Add
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmap
import androidx.navigation.NavHostController
import com.jihe.punchnet.data.AppAuthRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

data class AppInfo(
    val name: String,
    val packageName: String,
    val icon: Drawable
)

@Composable
fun AppAuthScreen(navController: NavHostController) {
    val context = LocalContext.current
    val allowedApps by AppAuthRepository.allowedApps.collectAsState()
    
    var installedApps by remember { mutableStateOf<List<AppInfo>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var showAppSelector by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            val pm = context.packageManager
            val intent = android.content.Intent(android.content.Intent.ACTION_MAIN, null).apply {
                addCategory(android.content.Intent.CATEGORY_LAUNCHER)
            }
            // Use queryIntentActivities to reliably find all user-facing apps
            val resolveInfos = pm.queryIntentActivities(intent, 0)
            val apps = resolveInfos.mapNotNull {
                try {
                    val appInfo = it.activityInfo.applicationInfo
                    if (appInfo.packageName != context.packageName) {
                        AppInfo(
                            name = it.loadLabel(pm).toString(),
                            packageName = appInfo.packageName,
                            icon = it.loadIcon(pm)
                        )
                    } else null
                } catch (e: Exception) {
                    null // Skip apps that cause PackageManager exceptions
                }
            }.distinctBy { it.packageName }.sortedBy { it.name }
            installedApps = apps
            isLoading = false
        }
    }

    if (showAppSelector) {
        // App Selection View
        Column(modifier = Modifier.fillMaxSize()) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                androidx.compose.material3.IconButton(onClick = { showAppSelector = false }) {
                    androidx.compose.material3.Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "返回"
                    )
                }
                Text("选择要代理的应用", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
            }
            
            if (isLoading) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Text("正在加载应用列表...")
                }
            } else {
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    items(installedApps) { app ->
                        val isAllowed = allowedApps.contains(app.packageName)
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp, vertical = 8.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Image(
                                bitmap = app.icon.toBitmap().asImageBitmap(),
                                contentDescription = app.name,
                                modifier = Modifier.size(40.dp)
                            )
                            Spacer(modifier = Modifier.width(16.dp))
                            Column(modifier = Modifier.weight(1f)) {
                                Text(text = app.name, fontWeight = FontWeight.Bold, fontSize = 16.sp)
                                Text(text = app.packageName, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
                            }
                            Switch(
                                checked = isAllowed,
                                onCheckedChange = { checked ->
                                    AppAuthRepository.toggleApp(context, app.packageName, checked)
                                }
                            )
                        }
                    }
                }
            }
        }
    } else {
        // Main View
        Box(modifier = Modifier.fillMaxSize()) {
            Column(modifier = Modifier.fillMaxSize()) {
                Text(
                    text = "只有在列表中的应用，其网络请求才会通过 PunchNet 代理。若列表为空，则默认代理所有应用。",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(16.dp)
                )
                
                val selectedApps = installedApps.filter { allowedApps.contains(it.packageName) }

                if (selectedApps.isEmpty() && !isLoading) {
                    Box(modifier = Modifier.fillMaxSize().padding(bottom = 80.dp), contentAlignment = Alignment.Center) {
                        Text("当前未选择任何应用\n(将代理全局流量)", textAlign = androidx.compose.ui.text.style.TextAlign.Center, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                } else {
                    LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 80.dp)) {
                        items(selectedApps) { app ->
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 16.dp, vertical = 8.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Image(
                                    bitmap = app.icon.toBitmap().asImageBitmap(),
                                    contentDescription = app.name,
                                    modifier = Modifier.size(40.dp)
                                )
                                Spacer(modifier = Modifier.width(16.dp))
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(text = app.name, fontWeight = FontWeight.Bold, fontSize = 16.sp)
                                    Text(text = app.packageName, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
                                }
                                androidx.compose.material3.IconButton(
                                    onClick = { AppAuthRepository.toggleApp(context, app.packageName, false) }
                                ) {
                                    androidx.compose.material3.Icon(
                                        imageVector = Icons.Default.Clear,
                                        contentDescription = "移除"
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // Add Button (FAB)
            androidx.compose.material3.FloatingActionButton(
                onClick = { showAppSelector = true },
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(16.dp)
            ) {
                androidx.compose.material3.Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "添加应用"
                )
            }
        }
    }
}
