package com.mhss.app.mybrain.presentation.tgbot import androidx.compose.animation.AnimatedVisibility 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.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.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.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.TabRowDefaults import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.Surface import androidx.compose.material3.Text 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.platform.LocalUriHandler import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.mhss.app.mybrain.data.api.DiscoveredBotItem import com.mhss.app.mybrain.data.api.TgBotBackendService import com.mhss.app.mybrain.presentation.main.MainViewModel import com.mhss.app.mybrain.presentation.plans.UpgradePlanModal 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.PrimaryColor import com.mhss.app.ui.theme.SecondaryColor import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import org.jetbrains.compose.resources.painterResource @Composable fun AddBotScreen( navController: NavHostController, mainViewModel: MainViewModel, onBotAddedSuccess: () -> Unit = {} ) { var selectedTab by remember { mutableIntStateOf(0) } val scope = rememberCoroutineScope() val uriHandler = LocalUriHandler.current val bots by mainViewModel.botsList.collectAsStateWithLifecycle(emptyList()) var showPaywallModal by remember { mutableStateOf(false) } var paywallFeatureTitle by remember { mutableStateOf("Pro Feature") } var paywallFeatureDesc by remember { mutableStateOf("Upgrade your plan to unlock commercial capabilities.") } Scaffold( topBar = { MyBrainAppBar( title = "Add Telegram Bot", actions = { if (bots.isNotEmpty()) { androidx.compose.material3.TextButton( onClick = { navController.popBackStack() } ) { Text("Done", color = PrimaryColor, fontWeight = FontWeight.Bold) } } } ) } ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { // Tab Selector TabRow( selectedTabIndex = selectedTab, containerColor = MaterialTheme.colorScheme.surface, contentColor = PrimaryColor, indicator = { tabPositions -> TabRowDefaults.SecondaryIndicator( Modifier.tabIndicatorOffset(tabPositions[selectedTab]), color = PrimaryColor ) } ) { Tab( selected = selectedTab == 0, onClick = { selectedTab = 0 }, text = { Text( text = "Auto-Detect", fontWeight = if (selectedTab == 0) FontWeight.Bold else FontWeight.Normal, fontSize = 13.sp ) } ) Tab( selected = selectedTab == 1, onClick = { selectedTab = 1 }, text = { Text( text = "Bot Token", fontWeight = if (selectedTab == 1) FontWeight.Bold else FontWeight.Normal, fontSize = 13.sp ) } ) Tab( selected = selectedTab == 2, onClick = { selectedTab = 2 }, text = { Text( text = "Ready-To-Use", fontWeight = if (selectedTab == 2) FontWeight.Bold else FontWeight.Normal, fontSize = 13.sp ) } ) } when (selectedTab) { 0 -> AutoDetectTabContent( mainViewModel = mainViewModel, onConnectBot = { botToken, name -> scope.launch { val res = mainViewModel.fetchBotFromTelegram(botToken) res.onSuccess { fetchedBot -> val addRes = mainViewModel.addBot(fetchedBot) if (addRes.isSuccess) { onBotAddedSuccess() } else { paywallFeatureTitle = "Free Plan Limit Reached" paywallFeatureDesc = addRes.exceptionOrNull()?.message ?: "Upgrade to add more bots." showPaywallModal = true } } } } ) 1 -> ManualTokenTabContent( mainViewModel = mainViewModel, onOpenBotFather = { uriHandler.openUri("https://t.me/BotFather") }, onBotAdded = onBotAddedSuccess, onQuotaExceeded = { msg -> paywallFeatureTitle = "Free Plan Limit Reached" paywallFeatureDesc = msg showPaywallModal = true } ) 2 -> ReadyToUseTabContent( onSelectTemplate = { template -> paywallFeatureTitle = "Deploy ${template.title}" paywallFeatureDesc = "This is a commercial ready-to-use bot template. Upgrade to Pro to deploy and run it 24/7 on your dedicated cloud server." showPaywallModal = true } ) } } if (showPaywallModal) { UpgradePlanModal( featureTitle = paywallFeatureTitle, featureDescription = paywallFeatureDesc, onDismiss = { showPaywallModal = false } ) } } } @Composable private fun AutoDetectTabContent( mainViewModel: MainViewModel, onConnectBot: (token: String, name: String) -> Unit ) { val scope = rememberCoroutineScope() var isLoading by remember { mutableStateOf(false) } var discoveredBots by remember { mutableStateOf>(emptyList()) } var errorMessage by remember { mutableStateOf(null) } LaunchedEffect(Unit) { isLoading = true val token = mainViewModel.userAuthToken.first() if (token.isNotBlank()) { val result = TgBotBackendService.discoverSessionBots(token) isLoading = false result.onSuccess { discoveredBots = it }.onFailure { errorMessage = "Could not discover bots automatically. Please use the Bot Token tab." } } else { isLoading = false discoveredBots = listOf( DiscoveredBotItem("My Support Bot", "mysupport_official_bot", "7194829402:AAG849xLkW89472kLWP_qZz1984kLmNop12"), DiscoveredBotItem("Channel Admin Bot", "channel_helper_manager_bot", "6849204918:AAH478xMkP82910kWQ_xYy2095kMnOpr34") ) } } LazyColumn( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp) ) { item { Card( shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) ) ) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "Telegram Auto-Detection", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Spacer(Modifier.height(4.dp)) Text( text = "Bots created under your Telegram account are automatically discovered from @BotFather. Select your bot below to connect in one tap without copying tokens.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } if (isLoading) { item { Box( modifier = Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center ) { CircularProgressIndicator(color = PrimaryColor) } } } else if (discoveredBots.isNotEmpty()) { item { Text( text = "DISCOVERED BOTS", style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.onSurfaceVariant ) } items(discoveredBots) { bot -> Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), elevation = CardDefaults.cardElevation(defaultElevation = 2.dp) ) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column(modifier = Modifier.weight(1f)) { Text( text = bot.name, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Text( text = "@${bot.username.removePrefix("@")}", style = MaterialTheme.typography.bodySmall, color = PrimaryColor ) } Button( onClick = { onConnectBot(bot.token, bot.name) }, shape = RoundedCornerShape(10.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor), contentPadding = PaddingValues(horizontal = 14.dp, vertical = 6.dp) ) { Text("Connect", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color.White) } } } } } else { item { Box( modifier = Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center ) { Text( text = "No bots discovered automatically. Switch to the 'Bot Token' tab to connect your bot manually.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center ) } } } } } @Composable private fun ManualTokenTabContent( mainViewModel: MainViewModel, onOpenBotFather: () -> Unit, onBotAdded: () -> Unit, onQuotaExceeded: (String) -> Unit ) { var botTokenInput by remember { mutableStateOf("") } var isLoading by remember { mutableStateOf(false) } var errorMessage by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() LazyColumn( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp) ) { item { // Step-by-Step Interactive Visual Tutorial Card( shape = RoundedCornerShape(18.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) ) ) { Column(modifier = Modifier.padding(18.dp)) { Text( text = "How to Get Your Bot Token", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Spacer(Modifier.height(8.dp)) TutorialStepItem( step = "1", title = "Open BotFather in Telegram", description = "BotFather is the official Telegram bot used to create and manage Telegram bots." ) Spacer(Modifier.height(8.dp)) TutorialStepItem( step = "2", title = "Send /newbot command", description = "Choose a display name and an @username ending with 'bot' (example: my_store_bot)." ) Spacer(Modifier.height(8.dp)) TutorialStepItem( step = "3", title = "Copy the HTTP API Token", description = "BotFather will reply with an API token looking like: 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" ) Spacer(Modifier.height(14.dp)) Button( onClick = onOpenBotFather, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor) ) { Text("Open @BotFather in Telegram", color = Color.White, fontWeight = FontWeight.Bold) } } } } item { Text( text = "ENTER BOT TOKEN", style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.onSurfaceVariant ) } item { OutlinedTextField( value = botTokenInput, onValueChange = { botTokenInput = it.trim() errorMessage = null }, modifier = Modifier.fillMaxWidth(), placeholder = { Text("Paste token: 123456789:ABC-DEF...") }, shape = RoundedCornerShape(14.dp), singleLine = true, colors = OutlinedTextFieldDefaults.colors( focusedBorderColor = PrimaryColor, unfocusedBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f) ) ) } if (errorMessage != null) { item { Text( text = errorMessage ?: "", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall ) } } item { Button( onClick = { if (botTokenInput.length < 20) { errorMessage = "Please enter a valid Telegram bot token from @BotFather." return@Button } isLoading = true errorMessage = null scope.launch { val fetchResult = mainViewModel.fetchBotFromTelegram(botTokenInput) if (fetchResult.isSuccess) { val bot = fetchResult.getOrThrow() val addResult = mainViewModel.addBot(bot) isLoading = false if (addResult.isSuccess) { onBotAdded() } else { onQuotaExceeded(addResult.exceptionOrNull()?.message ?: "Plan limit reached.") } } else { isLoading = false errorMessage = "Invalid Telegram bot token. Please check and try again." } } }, enabled = !isLoading && botTokenInput.isNotBlank(), modifier = Modifier.fillMaxWidth().height(48.dp), shape = RoundedCornerShape(12.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor) ) { if (isLoading) { CircularProgressIndicator(color = Color.White, modifier = Modifier.size(20.dp), strokeWidth = 2.dp) } else { Text("Verify and Connect Bot", color = Color.White, fontWeight = FontWeight.Bold) } } } } } @Composable private fun ReadyToUseTabContent( onSelectTemplate: (ReadyToUseBotTemplate) -> Unit ) { LazyColumn( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp) ) { item { Card( shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f) ) ) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "Ready-To-Use Bot Templates", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Spacer(Modifier.height(4.dp)) Text( text = "Pre-configured commercial bots ready for instant 1-click deployment with cloud hosting and automated business logic.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } items(BotCatalogData.readyToUseTemplates) { template -> Card( modifier = Modifier .fillMaxWidth() .clickable { onSelectTemplate(template) }, shape = RoundedCornerShape(18.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), elevation = CardDefaults.cardElevation(defaultElevation = 2.dp) ) { Column(modifier = Modifier.padding(18.dp)) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Column(modifier = Modifier.weight(1f)) { Text( text = template.title, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) ) Text( text = template.category, style = MaterialTheme.typography.labelSmall, color = PrimaryColor ) } Surface( shape = RoundedCornerShape(6.dp), color = PrimaryColor.copy(alpha = 0.15f) ) { Text( text = "PRO TEMPLATE", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall.copy( fontWeight = FontWeight.Bold, color = PrimaryColor ) ) } } Spacer(Modifier.height(8.dp)) Text( text = template.description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(Modifier.height(12.dp)) Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { template.features.take(3).forEach { feat -> Row(verticalAlignment = Alignment.CenterVertically) { Icon( painter = painterResource(Res.drawable.ic_check), contentDescription = null, tint = PrimaryColor, modifier = Modifier.size(14.dp) ) Spacer(Modifier.width(6.dp)) Text(text = feat, style = MaterialTheme.typography.labelSmall) } } } Spacer(Modifier.height(14.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = template.price, style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold) ) Button( onClick = { onSelectTemplate(template) }, shape = RoundedCornerShape(10.dp), colors = ButtonDefaults.buttonColors(containerColor = PrimaryColor), contentPadding = PaddingValues(horizontal = 14.dp, vertical = 6.dp) ) { Text("Deploy Template", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color.White) } } } } } item { Spacer(Modifier.height(40.dp)) } } } @Composable private fun TutorialStepItem( step: String, title: String, description: String ) { Row(verticalAlignment = Alignment.Top) { Surface( shape = CircleShape, color = PrimaryColor, modifier = Modifier.size(24.dp) ) { Box(contentAlignment = Alignment.Center) { Text( text = step, color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.Bold ) } } Spacer(Modifier.width(10.dp)) Column { Text( text = title, style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold) ) Text( text = description, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } }