package com.mhss.app.mybrain.presentation.admin import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.height 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.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.ScrollableTabRow import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Tab import androidx.compose.material3.TabRowDefaults import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.Text import androidx.compose.material3.TextButton import com.mhss.app.mybrain.presentation.auth.rememberGoogleSignInLauncher import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.mhss.app.ui.Res import com.mhss.app.ui.components.common.MyBrainAppBar import com.mhss.app.ui.ic_bolt import com.mhss.app.ui.ic_check import com.mhss.app.ui.theme.Green import com.mhss.app.ui.theme.Orange import com.mhss.app.ui.theme.PrimaryColor import com.mhss.app.ui.theme.Red import com.mhss.app.ui.theme.SecondaryColor import kotlinx.coroutines.launch import org.jetbrains.compose.resources.painterResource @Composable fun AdminScreen( onNavigateBack: () -> Unit = {} ) { var adminToken by remember { mutableStateOf(null) } var adminName by remember { mutableStateOf("Platform Administrator") } if (adminToken == null) { AdminLoginContent( onLoginSuccess = { token, name -> adminToken = token adminName = name }, onNavigateBack = onNavigateBack ) } else { AdminDashboardContent( adminToken = adminToken!!, adminName = adminName, onLogout = { adminToken = null }, onNavigateBack = onNavigateBack ) } } @Composable private fun AdminLoginContent( onLoginSuccess: (String, String) -> Unit, onNavigateBack: () -> Unit ) { var email by remember { mutableStateOf("admin@tgbotbuilder.com") } var password by remember { mutableStateOf("Admin@2026!") } var isLoading by remember { mutableStateOf(false) } var errorMessage by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() val infiniteTransition = rememberInfiniteTransition() val glowAlpha by infiniteTransition.animateFloat( initialValue = 0.4f, targetValue = 0.95f, animationSpec = infiniteRepeatable( animation = tween(1400), repeatMode = RepeatMode.Reverse ) ) Scaffold( topBar = { MyBrainAppBar( title = "Admin Authentication", actions = { TextButton(onClick = onNavigateBack) { Text("Exit", color = MaterialTheme.colorScheme.onSurfaceVariant) } } ) } ) { paddingValues -> Box( modifier = Modifier .fillMaxSize() .padding(paddingValues), contentAlignment = Alignment.Center ) { Card( modifier = Modifier .fillMaxWidth(0.92f) .border( width = 2.dp, brush = Brush.linearGradient( listOf( PrimaryColor.copy(alpha = glowAlpha), SecondaryColor.copy(alpha = glowAlpha) ) ), shape = RoundedCornerShape(24.dp) ), shape = RoundedCornerShape(24.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column( modifier = Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = Modifier .size(60.dp) .clip(CircleShape) .background(Brush.linearGradient(listOf(PrimaryColor, SecondaryColor))), contentAlignment = Alignment.Center ) { Text("ADM", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 18.sp) } Spacer(Modifier.height(14.dp)) Text( text = "TGBOT Master Control", style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold) ) Text( text = "Authorized Personnel Only", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(Modifier.height(20.dp)) OutlinedTextField( value = email, onValueChange = { email = it }, label = { Text("Admin Email") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) Spacer(Modifier.height(12.dp)) OutlinedTextField( value = password, onValueChange = { password = it }, label = { Text("Master Password / Secret") }, visualTransformation = PasswordVisualTransformation(), modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) if (errorMessage != null) { Spacer(Modifier.height(10.dp)) Text( text = errorMessage ?: "", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall, textAlign = TextAlign.Center ) } Spacer(Modifier.height(22.dp)) Button( onClick = { isLoading = true errorMessage = null scope.launch { val result = AdminBackendService.login(email.trim(), password.trim()) isLoading = false result.onSuccess { (token, name) -> onLoginSuccess(token, name) }.onFailure { err -> errorMessage = err.message ?: "Admin authentication failed" } } }, modifier = Modifier .fillMaxWidth() .height(50.dp), enabled = !isLoading, shape = RoundedCornerShape(14.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor) ) { if (isLoading) { CircularProgressIndicator(color = Color.White, modifier = Modifier.size(24.dp)) } else { Text("Sign In to Master Panel", fontWeight = FontWeight.Bold, color = Color.White) } } Spacer(Modifier.height(14.dp)) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Box(modifier = Modifier.weight(1f).height(1.dp).background(MaterialTheme.colorScheme.outline.copy(alpha = 0.2f))) Text( text = " OR ", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), fontWeight = FontWeight.SemiBold ) Box(modifier = Modifier.weight(1f).height(1.dp).background(MaterialTheme.colorScheme.outline.copy(alpha = 0.2f))) } Spacer(Modifier.height(14.dp)) val adminGoogleLauncher = rememberGoogleSignInLauncher( onSuccess = { result -> isLoading = true errorMessage = null scope.launch { val res = AdminBackendService.loginWithGoogle( email = result.email, fullName = result.displayName, idToken = result.idToken ) isLoading = false res.onSuccess { (token, name) -> onLoginSuccess(token, name) }.onFailure { err -> errorMessage = err.message ?: "Admin Google authentication failed" } } }, onError = { err -> errorMessage = err } ) OutlinedButton( onClick = { adminGoogleLauncher() }, modifier = Modifier .fillMaxWidth() .height(50.dp), shape = RoundedCornerShape(14.dp), enabled = !isLoading ) { Text( text = "Sign In with Google Admin", fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface ) } } } } } } @Composable private fun AdminDashboardContent( adminToken: String, adminName: String, onLogout: () -> Unit, onNavigateBack: () -> Unit ) { var selectedTab by remember { mutableIntStateOf(0) } val tabs = listOf("Server", "Users", "Bots", "Broadcast", "Settings") Scaffold( topBar = { MyBrainAppBar( title = "TGBOT Master Admin", actions = { Surface( shape = RoundedCornerShape(8.dp), color = Green.copy(alpha = 0.15f), modifier = Modifier.padding(end = 8.dp) ) { Text( text = "LIVE", color = Green, fontWeight = FontWeight.Bold, fontSize = 11.sp, modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) ) } TextButton(onClick = onLogout) { Text("Logout", color = Red) } } ) } ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { ScrollableTabRow( selectedTabIndex = selectedTab, containerColor = MaterialTheme.colorScheme.surface, contentColor = PrimaryColor, edgePadding = 12.dp, indicator = { tabPositions -> TabRowDefaults.SecondaryIndicator( Modifier.tabIndicatorOffset(tabPositions[selectedTab]), color = PrimaryColor ) } ) { tabs.forEachIndexed { index, title -> Tab( selected = selectedTab == index, onClick = { selectedTab = index }, text = { Text( text = title, fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal, color = if (selectedTab == index) PrimaryColor else MaterialTheme.colorScheme.onSurfaceVariant ) } ) } } when (selectedTab) { 0 -> AdminServerTab(adminToken) 1 -> AdminUsersTab(adminToken) 2 -> AdminBotsTab(adminToken) 3 -> AdminBroadcastTab(adminToken) 4 -> AdminSettingsTab(adminToken) } } } } @Composable private fun AdminServerTab(token: String) { val scope = rememberCoroutineScope() var overview by remember { mutableStateOf(null) } var isLoading by remember { mutableStateOf(false) } var errorMessage by remember { mutableStateOf(null) } fun refresh() { isLoading = true errorMessage = null scope.launch { val res = AdminBackendService.getOverview(token) isLoading = false res.onSuccess { overview = it } .onFailure { errorMessage = it.message } } } LaunchedEffect(Unit) { refresh() } if (isLoading && overview == null) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = PrimaryColor) } return } val ov = overview ?: AdminOverviewData() LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp) ) { item { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "System Diagnostics", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) OutlinedButton( onClick = { refresh() }, shape = RoundedCornerShape(10.dp), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp) ) { Text("Refresh", fontSize = 12.sp) } } } item { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(18.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), elevation = CardDefaults.cardElevation(2.dp) ) { Column(Modifier.padding(16.dp)) { Text("Resource Saturation", fontWeight = FontWeight.Bold, fontSize = 14.sp) Spacer(Modifier.height(12.dp)) // CPU Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("CPU Usage", style = MaterialTheme.typography.bodySmall) Text("${ov.system.cpu_percent}%", fontWeight = FontWeight.Bold, color = if (ov.system.cpu_percent > 80) Red else PrimaryColor) } LinearProgressIndicator( progress = { (ov.system.cpu_percent / 100.0).toFloat().coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)), color = if (ov.system.cpu_percent > 80) Red else PrimaryColor ) Spacer(Modifier.height(12.dp)) // RAM Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Memory (RAM)", style = MaterialTheme.typography.bodySmall) Text("${ov.system.ram_used_gb} GB / ${ov.system.ram_total_gb} GB (${ov.system.ram_percent}%)", fontWeight = FontWeight.Bold, color = SecondaryColor) } LinearProgressIndicator( progress = { (ov.system.ram_percent / 100.0).toFloat().coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)), color = SecondaryColor ) Spacer(Modifier.height(12.dp)) // Disk Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("NVMe Disk Storage", style = MaterialTheme.typography.bodySmall) Text("${ov.system.disk_used_gb} GB / ${ov.system.disk_total_gb} GB (${ov.system.disk_percent}%)", fontWeight = FontWeight.Bold) } LinearProgressIndicator( progress = { (ov.system.disk_percent / 100.0).toFloat().coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)), color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } item { Text("Business & Platform Overview", fontWeight = FontWeight.Bold, fontSize = 14.sp) } item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { AdminStatCard(title = "Registered Users", value = "${ov.metrics.total_users}", modifier = Modifier.weight(1f)) AdminStatCard(title = "Telegram Bots", value = "${ov.metrics.total_bots}", modifier = Modifier.weight(1f)) AdminStatCard(title = "Subscribers", value = "${ov.metrics.total_subscribers}", modifier = Modifier.weight(1f)) } } item { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Row( modifier = Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column { Text("Plans Breakdown", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Text( "Free: ${ov.metrics.plans.free} | Pro: ${ov.metrics.plans.pro} | Business: ${ov.metrics.plans.business}", fontWeight = FontWeight.Bold, fontSize = 13.sp ) } Surface( shape = RoundedCornerShape(8.dp), color = PrimaryColor.copy(alpha = 0.15f) ) { Text( text = "MRR: ₹${ov.metrics.estimated_mrr}", color = PrimaryColor, fontWeight = FontWeight.Bold, fontSize = 12.sp, modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) ) } } } } item { Text("PM2 Process Daemon Status", fontWeight = FontWeight.Bold, fontSize = 14.sp) } items(ov.system.pm2_services) { s -> Surface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), color = MaterialTheme.colorScheme.surface ) { Row( modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column { Text(s.name, fontWeight = FontWeight.Bold, fontSize = 13.sp) Text("Memory: ${s.memory_mb} MB | CPU: ${s.cpu_pct}%", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Surface( shape = RoundedCornerShape(6.dp), color = if (s.status == "online") Green.copy(alpha = 0.15f) else Red.copy(alpha = 0.15f) ) { Text( text = s.status.uppercase(), color = if (s.status == "online") Green else Red, fontWeight = FontWeight.Bold, fontSize = 11.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) ) } } } } } } @Composable private fun AdminStatCard(title: String, value: String, modifier: Modifier = Modifier) { Card( modifier = modifier, shape = RoundedCornerShape(14.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(12.dp)) { Text(title, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Spacer(Modifier.height(4.dp)) Text(value, fontWeight = FontWeight.Bold, fontSize = 18.sp, color = PrimaryColor) } } } @Composable private fun AdminUsersTab(token: String) { val scope = rememberCoroutineScope() var users by remember { mutableStateOf>(emptyList()) } var searchQuery by remember { mutableStateOf("") } var isLoading by remember { mutableStateOf(false) } var selectedUserForPlan by remember { mutableStateOf(null) } var userToDelete by remember { mutableStateOf(null) } fun refreshUsers() { isLoading = true scope.launch { val res = AdminBackendService.getUsers(token) isLoading = false res.onSuccess { users = it } } } LaunchedEffect(Unit) { refreshUsers() } val filtered = remember(users, searchQuery) { if (searchQuery.isBlank()) users else users.filter { it.email.contains(searchQuery, ignoreCase = true) || it.full_name.contains(searchQuery, ignoreCase = true) } } if (selectedUserForPlan != null) { val u = selectedUserForPlan!! AlertDialog( onDismissRequest = { selectedUserForPlan = null }, title = { Text("Update Subscription Tier") }, text = { Column { Text("Select new tier for ${u.email}:") Spacer(Modifier.height(12.dp)) listOf("free", "pro", "business").forEach { p -> Button( onClick = { scope.launch { AdminBackendService.updateUserPlan(token, u.id, p) selectedUserForPlan = null refreshUsers() } }, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), shape = RoundedCornerShape(10.dp), colors = ButtonDefaults.buttonColors( containerColor = if (u.plan_id.equals(p, ignoreCase = true)) PrimaryColor else MaterialTheme.colorScheme.surfaceVariant, contentColor = if (u.plan_id.equals(p, ignoreCase = true)) Color.White else MaterialTheme.colorScheme.onSurface ) ) { Text(p.uppercase() + if (p == "pro") " (₹499/mo)" else if (p == "business") " (₹1,499/mo)" else " (₹0)") } } } }, confirmButton = {}, dismissButton = { TextButton(onClick = { selectedUserForPlan = null }) { Text("Cancel") } } ) } if (userToDelete != null) { val u = userToDelete!! AlertDialog( onDismissRequest = { userToDelete = null }, title = { Text("Purge User Account?") }, text = { Text("Permanently delete user ${u.email} and all associated Telegram bots and sessions?") }, confirmButton = { Button( onClick = { scope.launch { AdminBackendService.deleteUser(token, u.id) userToDelete = null refreshUsers() } }, colors = ButtonDefaults.buttonColors(containerColor = Red) ) { Text("Confirm Delete", color = Color.White) } }, dismissButton = { OutlinedButton(onClick = { userToDelete = null }) { Text("Cancel") } } ) } Column(Modifier.fillMaxSize().padding(16.dp)) { OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, label = { Text("Search by user email or name") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) Spacer(Modifier.height(12.dp)) if (isLoading) { Box(Modifier.fillMaxWidth().height(100.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = PrimaryColor) } } else { LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp)) { items(filtered) { u -> Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(14.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(u.full_name, fontWeight = FontWeight.Bold, fontSize = 14.sp) Text(u.email, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Surface( shape = RoundedCornerShape(6.dp), color = if (u.plan_id == "business") SecondaryColor.copy(alpha = 0.2f) else if (u.plan_id == "pro") PrimaryColor.copy(alpha = 0.2f) else Color.Gray.copy(alpha = 0.2f) ) { Text( text = u.plan_id.uppercase(), fontWeight = FontWeight.Bold, fontSize = 11.sp, color = if (u.plan_id == "business") SecondaryColor else if (u.plan_id == "pro") PrimaryColor else Color.Gray, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) ) } } Spacer(Modifier.height(8.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Bots: ${u.bots_count} | Subscribers: ${u.subscribers_count}", style = MaterialTheme.typography.labelSmall) Surface( shape = RoundedCornerShape(4.dp), color = if (u.status == "active") Green.copy(alpha = 0.15f) else Red.copy(alpha = 0.15f) ) { Text( text = u.status.uppercase(), color = if (u.status == "active") Green else Red, fontWeight = FontWeight.Bold, fontSize = 10.sp, modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp) ) } } Spacer(Modifier.height(10.dp)) HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant) Spacer(Modifier.height(8.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { TextButton(onClick = { selectedUserForPlan = u }) { Text("Change Plan", fontSize = 12.sp, color = PrimaryColor, fontWeight = FontWeight.Bold) } Spacer(Modifier.width(4.dp)) TextButton(onClick = { scope.launch { val newStatus = if (u.status == "active") "suspended" else "active" AdminBackendService.updateUserStatus(token, u.id, newStatus) refreshUsers() } }) { Text(if (u.status == "active") "Suspend" else "Activate", fontSize = 12.sp, color = Orange) } Spacer(Modifier.width(4.dp)) TextButton(onClick = { userToDelete = u }) { Text("Delete", fontSize = 12.sp, color = Red) } } } } } } } } } @Composable private fun AdminBotsTab(token: String) { val scope = rememberCoroutineScope() var bots by remember { mutableStateOf>(emptyList()) } var searchQuery by remember { mutableStateOf("") } var isLoading by remember { mutableStateOf(false) } fun refreshBots() { isLoading = true scope.launch { val res = AdminBackendService.getBots(token) isLoading = false res.onSuccess { bots = it } } } LaunchedEffect(Unit) { refreshBots() } val filtered = remember(bots, searchQuery) { if (searchQuery.isBlank()) bots else bots.filter { it.name.contains(searchQuery, ignoreCase = true) || it.username.contains(searchQuery, ignoreCase = true) } } Column(Modifier.fillMaxSize().padding(16.dp)) { OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, label = { Text("Search bot name or @username") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) Spacer(Modifier.height(12.dp)) if (isLoading) { Box(Modifier.fillMaxWidth().height(100.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = PrimaryColor) } } else { LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp)) { items(filtered) { b -> Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(14.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text(b.name, fontWeight = FontWeight.Bold, fontSize = 14.sp) Text("@${b.username}", style = MaterialTheme.typography.bodySmall, color = PrimaryColor) } Surface( shape = RoundedCornerShape(6.dp), color = if (b.status == "active") Green.copy(alpha = 0.15f) else Orange.copy(alpha = 0.15f) ) { Text( text = b.status.uppercase(), color = if (b.status == "active") Green else Orange, fontWeight = FontWeight.Bold, fontSize = 11.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) ) } } Spacer(Modifier.height(8.dp)) Text("Tenant: ${b.tenant_name} | Subscribers: ${b.subscribers_count}", style = MaterialTheme.typography.labelSmall) Spacer(Modifier.height(10.dp)) HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant) Spacer(Modifier.height(8.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { TextButton(onClick = { scope.launch { AdminBackendService.executeBotAction(token, b.id, "restart") refreshBots() } }) { Text("Restart", fontSize = 12.sp, color = PrimaryColor) } Spacer(Modifier.width(4.dp)) TextButton(onClick = { scope.launch { AdminBackendService.executeBotAction(token, b.id, "stop") refreshBots() } }) { Text("Stop", fontSize = 12.sp, color = Orange) } Spacer(Modifier.width(4.dp)) TextButton(onClick = { scope.launch { AdminBackendService.executeBotAction(token, b.id, "delete") refreshBots() } }) { Text("Delete", fontSize = 12.sp, color = Red) } } } } } } } } } @Composable private fun AdminBroadcastTab(token: String) { var title by remember { mutableStateOf("") } var message by remember { mutableStateOf("") } var isSending by remember { mutableStateOf(false) } var successMsg by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp) ) { item { Text("Global App Announcement", fontWeight = FontWeight.Bold, fontSize = 16.sp) Text( "Broadcasts a message instantly to all users running the Android app.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } item { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(16.dp)) { OutlinedTextField( value = title, onValueChange = { title = it }, label = { Text("Announcement Title") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) Spacer(Modifier.height(12.dp)) OutlinedTextField( value = message, onValueChange = { message = it }, label = { Text("Announcement Body") }, modifier = Modifier.fillMaxWidth().height(120.dp), shape = RoundedCornerShape(12.dp) ) if (successMsg != null) { Spacer(Modifier.height(10.dp)) Text(successMsg ?: "", color = Green, fontWeight = FontWeight.Bold, fontSize = 13.sp) } Spacer(Modifier.height(16.dp)) Button( onClick = { if (title.isNotBlank() && message.isNotBlank()) { isSending = true successMsg = null scope.launch { val res = AdminBackendService.broadcastAnnouncement(token, title.trim(), message.trim()) isSending = false res.onSuccess { successMsg = "Broadcast published to all app instances!" title = "" message = "" } } } }, modifier = Modifier.fillMaxWidth().height(48.dp), shape = RoundedCornerShape(12.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor), enabled = !isSending && title.isNotBlank() && message.isNotBlank() ) { if (isSending) { CircularProgressIndicator(color = Color.White, modifier = Modifier.size(20.dp)) } else { Text("Dispatch Global Broadcast", color = Color.White, fontWeight = FontWeight.Bold) } } } } } } } @Composable private fun AdminSettingsTab(token: String) { var config by remember { mutableStateOf(AdminAppConfig()) } var isLoading by remember { mutableStateOf(false) } var statusMessage by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() LaunchedEffect(Unit) { isLoading = true scope.launch { val res = AdminBackendService.getConfig(token) isLoading = false res.onSuccess { config = it } } } LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp) ) { item { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(16.dp)) { Text("Master Feature Switchboard", fontWeight = FontWeight.Bold, fontSize = 16.sp) Spacer(Modifier.height(4.dp)) Text( "Toggle any platform feature on or off in real-time. Changes sync immediately to all clients and Firebase.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(Modifier.height(14.dp)) FeatureToggleRow("AI Bot Synthesizer", "AI-powered bot generation via LLMs", config.ai_bot_creation) { config = config.copy(ai_bot_creation = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Telegram Session Login", "Direct MTProto phone code verification", config.telegram_session_login) { config = config.copy(telegram_session_login = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Telegram Web Widget Auth", "Official Telegram web widget login", config.telegram_web_login) { config = config.copy(telegram_web_login = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Bot Marketplace & Store", "Community templates and pre-built bots", config.bot_marketplace) { config = config.copy(bot_marketplace = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Billing & Payment Gateways", "Razorpay, Stripe and UPI subscriptions", config.payment_gateway) { config = config.copy(payment_gateway = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("MCP & Advanced Plugins", "Model Context Protocol tool execution", config.mcp_tools) { config = config.copy(mcp_tools = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Broadcast Studio", "Mass announcements and messaging", config.broadcast_studio) { config = config.copy(broadcast_studio = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Public User Registrations", "Allow new users to sign up", config.user_registration) { config = config.copy(user_registration = it) } HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), modifier = Modifier.padding(vertical = 8.dp)) FeatureToggleRow("Free Tier Access", "Allow zero-cost bot creation", config.free_tier_enabled) { config = config.copy(free_tier_enabled = it) } Spacer(Modifier.height(16.dp)) Button( onClick = { scope.launch { val res = AdminBackendService.updateConfig(token, config) res.onSuccess { statusMessage = "All feature switches updated and synced" } .onFailure { statusMessage = "Update failed: ${it.message}" } } }, modifier = Modifier.fillMaxWidth().height(48.dp), shape = RoundedCornerShape(12.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor) ) { Text("Apply Master Switches", color = Color.White, fontWeight = FontWeight.Bold) } } } } item { var serverOpMsg by remember { mutableStateOf(null) } var isExecutingOp by remember { mutableStateOf(false) } Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(16.dp)) { Text("Server Operations & Cache", fontWeight = FontWeight.Bold, fontSize = 16.sp) Spacer(Modifier.height(4.dp)) Text( "Manage Redis cache, restart background worker processes, or force Firestore sync.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) if (serverOpMsg != null) { Spacer(Modifier.height(10.dp)) Text(serverOpMsg ?: "", color = Green, fontWeight = FontWeight.Bold, fontSize = 12.sp) } Spacer(Modifier.height(14.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedButton( onClick = { isExecutingOp = true scope.launch { val res = AdminBackendService.executeServerAction(token, "clear_cache") isExecutingOp = false res.onSuccess { serverOpMsg = "Cache cleared successfully" } .onFailure { serverOpMsg = "Failed: ${it.message}" } } }, modifier = Modifier.weight(1f), shape = RoundedCornerShape(10.dp), enabled = !isExecutingOp ) { Text("Flush Cache", fontSize = 11.sp, maxLines = 1) } OutlinedButton( onClick = { isExecutingOp = true scope.launch { val res = AdminBackendService.executeServerAction(token, "restart_workers") isExecutingOp = false res.onSuccess { serverOpMsg = "Workers restart initiated" } .onFailure { serverOpMsg = "Failed: ${it.message}" } } }, modifier = Modifier.weight(1f), shape = RoundedCornerShape(10.dp), enabled = !isExecutingOp ) { Text("Restart Workers", fontSize = 11.sp, maxLines = 1) } OutlinedButton( onClick = { isExecutingOp = true scope.launch { val res = AdminBackendService.executeServerAction(token, "sync_firebase") isExecutingOp = false res.onSuccess { serverOpMsg = "Firestore synced" } .onFailure { serverOpMsg = "Failed: ${it.message}" } } }, modifier = Modifier.weight(1f), shape = RoundedCornerShape(10.dp), enabled = !isExecutingOp ) { Text("Sync Firestore", fontSize = 11.sp, maxLines = 1) } } } } } item { Text("Platform Policies & Version Control", fontWeight = FontWeight.Bold, fontSize = 16.sp) } item { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(16.dp)) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column(Modifier.weight(1f)) { Text("Maintenance Mode", fontWeight = FontWeight.Bold) Text("Lock client app for scheduled maintenance", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } Switch( checked = config.maintenance_mode, onCheckedChange = { config = config.copy(maintenance_mode = it) }, colors = SwitchDefaults.colors(checkedThumbColor = PrimaryColor) ) } Spacer(Modifier.height(14.dp)) OutlinedTextField( value = config.min_version, onValueChange = { config = config.copy(min_version = it) }, label = { Text("Minimum App Version Required") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) Spacer(Modifier.height(12.dp)) OutlinedTextField( value = config.notice, onValueChange = { config = config.copy(notice = it) }, label = { Text("Emergency Notice / Banner Text") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) if (statusMessage != null) { Spacer(Modifier.height(10.dp)) Text(statusMessage ?: "", color = Green, fontWeight = FontWeight.Bold, fontSize = 13.sp) } Spacer(Modifier.height(16.dp)) Button( onClick = { scope.launch { val res = AdminBackendService.updateConfig(token, config) res.onSuccess { statusMessage = "Platform policies saved successfully" } } }, modifier = Modifier.fillMaxWidth().height(48.dp), shape = RoundedCornerShape(12.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor) ) { Text("Save Policies", color = Color.White, fontWeight = FontWeight.Bold) } } } } item { var dynamicApiUrl by remember { mutableStateOf(AdminBackendService.BASE_URL) } var apiUpdateMsg by remember { mutableStateOf(null) } var isUpdatingApi by remember { mutableStateOf(false) } Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column(Modifier.padding(16.dp)) { Text("Dynamic Firebase API Endpoint", fontWeight = FontWeight.Bold, fontSize = 15.sp) Spacer(Modifier.height(4.dp)) Text( "Updating this URL writes directly to Firebase Firestore. All client APKs dynamically fetch and route to this URL without requiring a new APK release.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(Modifier.height(12.dp)) OutlinedTextField( value = dynamicApiUrl, onValueChange = { dynamicApiUrl = it }, label = { Text("Server API Base URL") }, modifier = Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(12.dp) ) if (apiUpdateMsg != null) { Spacer(Modifier.height(8.dp)) Text(apiUpdateMsg ?: "", color = Green, fontWeight = FontWeight.Bold, fontSize = 12.sp) } Spacer(Modifier.height(12.dp)) Button( onClick = { if (dynamicApiUrl.isNotBlank()) { isUpdatingApi = true scope.launch { val res = AdminBackendService.updateFirebaseApiUrl(token, dynamicApiUrl) isUpdatingApi = false res.onSuccess { apiUpdateMsg = "API URL updated in Firebase successfully" }.onFailure { apiUpdateMsg = "Failed to update Firebase: ${it.message}" } } } }, enabled = !isUpdatingApi, modifier = Modifier.fillMaxWidth().height(46.dp), shape = RoundedCornerShape(12.dp), colors = ButtonDefaults.buttonColors(containerColor = SecondaryColor) ) { Text("Update API in Firebase", color = Color.White, fontWeight = FontWeight.Bold) } } } } } } @Composable private fun FeatureToggleRow( title: String, subtitle: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column(Modifier.weight(1f).padding(end = 12.dp)) { Text(title, fontWeight = FontWeight.SemiBold, fontSize = 14.sp) Text(subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 11.sp) } Switch( checked = checked, onCheckedChange = onCheckedChange, colors = SwitchDefaults.colors(checkedThumbColor = PrimaryColor) ) } }