package com.aiosman.ravenow.ui.group

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
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.foundation.text.BasicTextField
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
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.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.PointsPaymentDialog
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.index.NavItem
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToAddGroupMember
import com.aiosman.ravenow.ui.navigateToGroupMembers
import com.aiosman.ravenow.ui.navigateToGroupProfileSettings
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GroupChatInfoScreen(groupId: String) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val AppColors = LocalAppTheme.current
    
    val viewModel = viewModel<GroupChatInfoViewModel>(
        key = "GroupChatInfoViewModel_$groupId",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return GroupChatInfoViewModel(groupId) as T
            }
        }
    )
    
    var showAddMemoryDialog by remember { mutableStateOf(false) }
    var showMemoryManageDialog by remember { mutableStateOf(false) }
    var showVisibilityDialog by remember { mutableStateOf(false) }
    var showVisibilityPaymentDialog by remember { mutableStateOf(false) }
    var pendingIsPrivate by remember { mutableStateOf(false) }
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val memoryManageSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        // 顶部导航栏
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(AppColors.background)
        ) {
            StatusBarSpacer()
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 12.dp, horizontal = 12.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(R.drawable.rider_pro_back_icon),
                    modifier = Modifier
                        .size(24.dp)
                        .noRippleClickable {
                            navController.navigateUp()
                        },
                    contentDescription = null,
                    colorFilter = ColorFilter.tint(AppColors.text)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Start,
                    text = stringResource(R.string.group_chat_info_title),
                    style = androidx.compose.ui.text.TextStyle(
                        color = AppColors.text,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                )
            }
        }
        
        // 内容区域
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            contentPadding = PaddingValues(12.dp)
        ) {
            // 群聊头像和名称
            item {
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    if (viewModel.groupInfo?.groupAvatar?.isNotEmpty() == true) {
                        CustomAsyncImage(
                            imageUrl = viewModel.groupInfo!!.groupAvatar,
                            modifier = Modifier
                                .size(64.dp)
                                .clip(RoundedCornerShape(12.dp)),
                            contentDescription = "群聊头像"
                        )
                    } else {
                        Box(
                            modifier = Modifier
                                .size(80.dp)
                                .clip(RoundedCornerShape(12.dp))
                                .background(AppColors.decentBackground),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = viewModel.groupInfo?.groupName?.firstOrNull()?.toString() ?: "",
                                style = androidx.compose.ui.text.TextStyle(
                                    color = AppColors.text,
                                    fontSize = 24.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = viewModel.groupInfo?.groupName ?: stringResource(R.string.group_info_edit),
                        style = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold
                        )
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Image(
                            painter = painterResource(R.drawable.group_info_users),
                            modifier = Modifier.size(12.dp),
                            contentDescription = null,
                            colorFilter = ColorFilter.tint(AppColors.text.copy(alpha = 0.7f))
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "${viewModel.groupInfo?.memberCount ?: 0}${stringResource(R.string.people)}",
                            style = androidx.compose.ui.text.TextStyle(
                                color = AppColors.text.copy(alpha = 0.7f),
                                fontSize = 11.sp
                            )
                        )
                    }
                }
            }
            
            // 操作按钮
            item {
                Spacer(modifier = Modifier.height(10.dp))
                Row(
                    modifier = Modifier
                        .padding(horizontal = 24.dp)
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    if (viewModel.groupInfo?.isCreator == true) {
                        // 添加其他人
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            modifier = Modifier.noRippleClickable {
                                navController.navigateToAddGroupMember(groupId, viewModel.groupInfo?.groupName)
                            }
                        ) {
                            Box(
                                modifier = Modifier
                                    .size(30.dp)
                                    .clip(CircleShape),
                                contentAlignment = Alignment.Center
                            ) {
                                Image(
                                    painter = painterResource(R.drawable.rider_pro_add_other),
                                    modifier = Modifier.size(20.dp),
                                    contentDescription = null,
                                    colorFilter = ColorFilter.tint(
                                        AppColors.text)
                                )
                            }
                            Spacer(modifier = Modifier.height(5.dp))
                            Text(
                                text = stringResource(R.string.group_chat_info_add_member),
                                style = androidx.compose.ui.text.TextStyle(
                                    color = AppColors.text,
                                    fontSize = 11.sp
                                )
                            )
                        }
                    }
                    
                    // 通知设置
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.noRippleClickable {
                            viewModel.viewModelScope.launch {
                                /*if (viewModel.notificationStrategy == "mute") {
                                    viewModel.updateNotificationStrategy("active")
                                } else {
                                    viewModel.updateNotificationStrategy("mute")
                                }*/
                            }
                        }
                    ) {
                        Box(
                            modifier = Modifier
                                .size(30.dp)
                                .clip(CircleShape),
                            contentAlignment = Alignment.Center
                        ) {
                            Image(
                                painter = painterResource(if (viewModel.notificationStrategy == "mute") R.drawable.rider_pro_notice_mute else R.drawable.rider_pro_notice_active,),
                                modifier = Modifier.size(20.dp),
                                contentDescription = null,
                                colorFilter = ColorFilter.tint(
                                    AppColors.text)
                            )
                        }
                        Spacer(modifier = Modifier.height(5.dp))
                        Text(
                            text = stringResource(R.string.group_chat_info_notification),
                            style = androidx.compose.ui.text.TextStyle(
                                color = AppColors.text,
                                fontSize = 11.sp
                            )
                        )
                    }
                    
                    // 分享群聊
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.noRippleClickable {
                            // TODO: 实现分享功能
                        }
                    ) {
                        Box(
                            modifier = Modifier
                                .size(30.dp)
                                .clip(CircleShape),
                            contentAlignment = Alignment.Center
                        ) {
                            Image(
                                painter = painterResource(R.mipmap.icon_share),
                                modifier = Modifier.size(20.dp),
                                contentDescription = null,
                                colorFilter = ColorFilter.tint(AppColors.text)
                            )
                        }
                        Spacer(modifier = Modifier.height(5.dp))
                        Text(
                            text = stringResource(R.string.group_chat_info_share),
                            style = androidx.compose.ui.text.TextStyle(
                                color = AppColors.text,
                                fontSize = 11.sp
                            )
                        )
                    }
                }
            }


            // 群记忆 卡片
            item {
                Spacer(modifier = Modifier.height(12.dp))
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(12.dp))
                        .background(AppColors.decentBackground.copy(alpha = 0.28f))
                        .padding(12.dp)
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Image(
                            painter = painterResource(R.mipmap.icons_brain),
                            modifier = Modifier.size(20.dp),
                            contentDescription = null,
                        )
                        Spacer(modifier = Modifier.width(6.dp))
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                text = stringResource(R.string.group_chat_info_group_memory),
                                style = androidx.compose.ui.text.TextStyle(
                                    color = AppColors.text,
                                    fontSize = 15.sp,
                                )
                            )
                            Spacer(modifier = Modifier.height(2.dp))
                            Text(
                                text = stringResource(R.string.group_chat_info_memory_description),
                                style = androidx.compose.ui.text.TextStyle(
                                    color = AppColors.text.copy(alpha = 0.6f),
                                    fontSize = 11.sp
                                )
                            )
                        }
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .clip(RoundedCornerShape(20.dp))
                                .background(AppColors.background)
                                .padding(vertical = 8.dp)
                                .noRippleClickable {
                                    showAddMemoryDialog = true
                                },
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = stringResource(R.string.group_chat_info_add_memory),
                                style = androidx.compose.ui.text.TextStyle(
                                    color = AppColors.text,
                                    fontSize = 13.sp
                                )
                            )
                        }
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .clip(RoundedCornerShape(20.dp))
                                .background(AppColors.background)
                                .padding(vertical = 8.dp)
                                .noRippleClickable {
                                    showMemoryManageDialog = true
                                },
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = stringResource(R.string.group_chat_info_memory_manage),
                                style = androidx.compose.ui.text.TextStyle(
                                    color = AppColors.text,
                                    fontSize = 13.sp
                                )
                            )
                        }
                    }
                }
            }

            // 设置选项
            item {
                Spacer(modifier = Modifier.height(13.dp))
                
                // 仅当当前用户是群聊创建者时显示以下组件
                if (viewModel.groupInfo?.isCreator == true) {
                    // 群资料设置
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(8.dp))
                            .padding(12.dp)
                            .noRippleClickable {
                                navController.navigateToGroupProfileSettings(groupId)
                            },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.fengm),
                            modifier = Modifier.size(20.dp),
                            contentDescription = null,
                            colorFilter = ColorFilter.tint(
                                AppColors.text)
                        )
                        Spacer(modifier = Modifier.width(10.dp))
                        Text(
                            text = stringResource(R.string.group_chat_info_group_settings),
                            style = androidx.compose.ui.text.TextStyle(
                                color = AppColors.text,
                                fontSize = 15.sp
                            ),
                            modifier = Modifier.weight(1f)
                        )
                        Image(
                            painter = painterResource(R.drawable.rave_now_nav_right),
                            modifier = Modifier.size(16.dp),
                            contentDescription = null,
                        )
                    }
                    
                    // 群可见性
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(8.dp))
                            .padding(12.dp)
                            .noRippleClickable {
                                showVisibilityDialog = true
                            },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.rider_pro_change_password),
                            modifier = Modifier.size(20.dp),
                            contentDescription = null,
                            colorFilter = ColorFilter.tint(AppColors.text)
                        )
                        Spacer(modifier = Modifier.width(10.dp))
                        Text(
                            text = stringResource(R.string.group_chat_info_group_visibility),
                            style = androidx.compose.ui.text.TextStyle(
                                color = AppColors.text,
                                fontSize = 15.sp
                            ),
                            modifier = Modifier.weight(1f)
                        )
                        // 未解锁时才显示"待解锁"
                        if (viewModel.groupInfo?.privateFeePaid != true) {
                        Text(
                            text = stringResource(R.string.group_chat_info_locked),
                            style = androidx.compose.ui.text.TextStyle(
                                color = AppColors.text.copy(alpha = 0.5f),
                                fontSize = 11.sp
                            )
                        )
                        }
                        Image(
                            painter = painterResource(R.drawable.rave_now_nav_right),
                            modifier = Modifier.size(16.dp),
                            contentDescription = null,
                        )
                    }
                }

                // 成员管理
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(8.dp))
                        .padding(12.dp)
                        .noRippleClickable {
                            navController.navigateToGroupMembers(groupId)
                        },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        painter = painterResource(R.mipmap.icons_users),
                        modifier = Modifier.size(25.dp),
                        contentDescription = null,
                        colorFilter = ColorFilter.tint(
                            AppColors.text)
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(
                        text = stringResource(
                            if (viewModel.groupInfo?.isCreator == true) {
                                R.string.group_chat_info_member_manage
                            } else {
                                R.string.group_members_title
                            }
                        ),
                        style = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text,
                            fontSize = 15.sp
                        ),
                        modifier = Modifier.weight(1f)
                    )
                    Image(
                        painter = painterResource(R.drawable.rave_now_nav_right),
                        modifier = Modifier.size(16.dp),
                        contentDescription = null,
                    )
                }
                // 群聊壁纸
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(8.dp))
                        .padding(12.dp)
                        .noRippleClickable { },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        painter = painterResource(R.mipmap.iconsgallery),
                        modifier = Modifier.size(25.dp),
                        contentDescription = null,
                        colorFilter = ColorFilter.tint(
                            AppColors.text)
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(
                        text = stringResource(R.string.group_chat_info_wallpaper),
                        style = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text,
                            fontSize = 15.sp
                        ),
                        modifier = Modifier.weight(1f)
                    )
                    Image(
                        painter = painterResource(R.drawable.rave_now_nav_right),
                        modifier = Modifier.size(18.dp),
                        contentDescription = null,
                    )
                }
                if (viewModel.groupInfo?.isCreator == true) {
                    // 解散群聊（仅群主）
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(8.dp))
                            .padding(12.dp)
                            .noRippleClickable { },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Spacer(modifier = Modifier.width(3.dp))
                        Image(
                            painter = painterResource(R.mipmap.iconslogout),
                            modifier = Modifier.size(20.dp),
                            contentDescription = null,
                            colorFilter = ColorFilter.tint(Color(0xFFFF3B30))
                        )
                        Spacer(modifier = Modifier.width(11.dp))
                        Text(
                            text = stringResource(R.string.group_chat_info_dissolve),
                            style = androidx.compose.ui.text.TextStyle(
                                color = Color(0xFFFF3B30),
                                fontSize = 15.sp
                            ),
                            modifier = Modifier.weight(1f)
                        )
                        Image(
                            painter = painterResource(R.drawable.rave_now_nav_right),
                            modifier = Modifier.size(18.dp),
                            contentDescription = null
                        )
                    }
                } else {
                    // 退出群聊（非群主）
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(8.dp))
                            .padding(12.dp)
                            .noRippleClickable { },
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Spacer(modifier = Modifier.width(3.dp))
                        Image(
                            painter = painterResource(R.drawable.group_info_exit),
                            modifier = Modifier.size(20.dp),
                            contentDescription = null,
                            colorFilter = ColorFilter.tint(Color(0xFFFF3B30))
                        )
                        Spacer(modifier = Modifier.width(11.dp))
                        Text(
                            text = stringResource(R.string.group_chat_info_quit),
                            style = androidx.compose.ui.text.TextStyle(
                                color = Color(0xFFFF3B30),
                                fontSize = 15.sp
                            ),
                            modifier = Modifier.weight(1f)
                        )
                        Image(
                            painter = painterResource(R.drawable.rave_now_nav_right),
                            modifier = Modifier.size(18.dp),
                            contentDescription = null
                        )
                    }
                }
            }
        }
    }
    
    // 群可见性弹窗
    if (showVisibilityDialog) {
        val visibilitySheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
        ModalBottomSheet(
            onDismissRequest = { showVisibilityDialog = false },
            sheetState = visibilitySheetState,
            containerColor = Color(0xFFFAF9FB),
            dragHandle = {
                Box(
                    modifier = Modifier
                        .width(36.dp)
                        .height(5.dp)
                        .padding(top = 5.dp)
                        .background(
                            Color(0xFFCCCCCC),
                            RoundedCornerShape(100.dp)
                        )
                )
            },
            shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
        ) {
            GroupVisibilityDialog(
                viewModel = viewModel,
                onDismiss = { showVisibilityDialog = false },
                onConfirmPrivate = { isPrivate ->
                    // 如果选择私密群组且未解锁，显示付费确认弹框
                    if (isPrivate && (viewModel.groupInfo?.privateFeePaid != true)) {
                        pendingIsPrivate = true
                        showVisibilityDialog = false
                        showVisibilityPaymentDialog = true
                    } else {
                        // 直接更新可见性
                        viewModel.updateVisibility(isPrivate)
                        showVisibilityDialog = false
                    }
                }
            )
        }
    }
    
    // 付费确认弹框
    if (showVisibilityPaymentDialog) {
        val cost = viewModel.privateGroupCost ?: 0
        val currentBalance = viewModel.pointsBalance ?: 0
        val balanceAfterCost = (currentBalance - cost).coerceAtLeast(0)
        val isBalanceSufficient = currentBalance >= cost
        
        PointsPaymentDialog(
            cost = cost,
            currentBalance = currentBalance,
            balanceAfterCost = balanceAfterCost,
            isBalanceSufficient = isBalanceSufficient,
            onConfirm = {
                // 确认支付，更新可见性
                viewModel.updateVisibility(pendingIsPrivate)
                showVisibilityPaymentDialog = false
            },
            onCancel = {
                showVisibilityPaymentDialog = false
            },
            title = stringResource(R.string.group_chat_info_private_group),
            description = stringResource(R.string.group_chat_info_private_group_desc),
            isProcessing = viewModel.isUpdatingVisibility
        )
    }
    
    // 添加群记忆弹窗
    if (showAddMemoryDialog) {
        ModalBottomSheet(
            onDismissRequest = { showAddMemoryDialog = false },
            sheetState = sheetState,
            containerColor = Color(0xFFFAF9FB),
            dragHandle = {
                Box(
                    modifier = Modifier
                        .width(36.dp)
                        .height(5.dp)
                        .padding(top = 5.dp)
                        .background(
                            Color(0xFFCCCCCC),
                            RoundedCornerShape(100.dp)
                        )
                )
            },
            shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
        ) {
            AddGroupMemoryDialog(
                groupInfo = viewModel.groupInfo,
                viewModel = viewModel,
                onDismiss = { showAddMemoryDialog = false },
                onAddMemory = { memoryText ->
                    viewModel.addGroupMemory(memoryText)
                }
            )
        }
    }
    
    // 记忆管理弹窗
    if (showMemoryManageDialog) {
        ModalBottomSheet(
            onDismissRequest = { showMemoryManageDialog = false },
            sheetState = memoryManageSheetState,
            containerColor = Color(0xFFFAF9FB),
            dragHandle = {
                Box(
                    modifier = Modifier
                        .width(36.dp)
                        .height(5.dp)
                        .padding(top = 5.dp)
                        .background(
                            Color(0xFFCCCCCC),
                            RoundedCornerShape(100.dp)
                        )
                )
            },
            shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
        ) {
            // 立即展开到全屏，避免逐渐变高的动画
            LaunchedEffect(Unit) {
                memoryManageSheetState.expand()
            }
            GroupMemoryManageContent(
                groupId = groupId,
                viewModel = viewModel,
                onAddMemoryClick = {
                    showMemoryManageDialog = false
                    showAddMemoryDialog = true
                },
                onDismiss = {
                    showMemoryManageDialog = false
                }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddGroupMemoryDialog(
    groupInfo: com.aiosman.ravenow.entity.GroupInfo?,
    viewModel: GroupChatInfoViewModel,
    onDismiss: () -> Unit,
    onAddMemory: (String) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    var memoryText by remember { mutableStateOf("") }
    val maxLength = 500
    
    // 监听添加记忆的结果
    LaunchedEffect(viewModel.addMemorySuccess) {
        if (viewModel.addMemorySuccess) {
            android.widget.Toast.makeText(context, context.getString(R.string.group_chat_info_memory_add_success), android.widget.Toast.LENGTH_SHORT).show()
            memoryText = "" // 清空输入框
            onDismiss()
            viewModel.addMemorySuccess = false
        }
    }
    
    LaunchedEffect(viewModel.addMemoryError) {
        viewModel.addMemoryError?.let { error ->
            android.widget.Toast.makeText(context, error, android.widget.Toast.LENGTH_SHORT).show()
            viewModel.addMemoryError = null
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .padding(bottom = 40.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 顶部标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(44.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Spacer(modifier = Modifier.width(24.dp))
            Text(
                text = stringResource(R.string.group_chat_info_add_group_memory),
                style = TextStyle(
                    fontSize = 17.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.Black
                ),
                modifier = Modifier.weight(1f),
                textAlign = TextAlign.Center
            )
            Image(
                painter = painterResource(R.drawable.rider_pro_close),
                contentDescription = "关闭",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable { onDismiss() },
                colorFilter = ColorFilter.tint(Color.Black)
            )
        }
        
        Spacer(modifier = Modifier.height(10.dp))
        
        Column(
            modifier = Modifier.fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 群信息卡片
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(80.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color.White)
                    .padding(horizontal = 12.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                if (groupInfo?.groupAvatar?.isNotEmpty() == true) {
                    CustomAsyncImage(
                        imageUrl = groupInfo.groupAvatar,
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(12.dp)),
                        contentDescription = "群头像"
                    )
                } else {
                    Box(
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(12.dp))
                            .background(AppColors.decentBackground),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = groupInfo?.groupName?.firstOrNull()?.toString() ?: "",
                            style = TextStyle(
                                fontSize = 20.sp,
                                fontWeight = FontWeight.Bold,
                                color = AppColors.text
                            )
                        )
                    }
                }
                
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Text(
                        text = groupInfo?.groupName ?: "",
                        style = TextStyle(
                            fontSize = 15.sp,
                            fontWeight = FontWeight.SemiBold,
                            color = Color.Black
                        )
                    )
                    Text(
                        text = stringResource(R.string.group_chat_info_member_count, groupInfo?.memberCount ?: 32),
                        style = TextStyle(
                            fontSize = 12.sp,
                            color = Color(0xFF3C3C43).copy(alpha = 0.6f)
                        )
                    )
                }
            }
            
            // 输入框卡片
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color.White)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(84.dp),
                        contentAlignment = Alignment.TopStart
                    ) {
                        BasicTextField(
                            value = memoryText,
                            onValueChange = { newText ->
                                if (newText.length <= maxLength) {
                                    memoryText = newText
                                }
                            },
                            cursorBrush = SolidColor(Color.Black),
                            modifier = Modifier.fillMaxWidth(),
                            maxLines = 6,
                            textStyle = TextStyle(
                                fontSize = 15.sp,
                                color = Color.Black,
                                lineHeight = 20.sp
                            ),
                            decorationBox = { innerTextField ->
                                Box(
                                    modifier = Modifier.fillMaxWidth(),
                                    contentAlignment = Alignment.TopStart
                                ) {
                                    innerTextField()
                                    if (memoryText.isEmpty()) {
                                        Text(
                                            text = stringResource(R.string.group_chat_info_memory_input_hint),
                                            style = TextStyle(
                                                fontSize = 15.sp,
                                                color = Color.Black.copy(alpha = 0.3f)
                                            )
                                        )
                                    }
                                }
                            }
                        )
                    }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        Text(
                            text = "${memoryText.length}/$maxLength",
                            style = TextStyle(
                                fontSize = 12.sp,
                                color = Color(0xFF3C3C43).copy(alpha = 0.3f)
                            )
                        )
                    }
                }
            }
            
            // 提示信息卡片
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color(0xFFFBF8EF))
                    .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "⭐",
                        fontSize = 13.sp
                    )
                    val memoryCost = viewModel.addMemoryCost
                    Text(
                        text = if (memoryCost != null && memoryCost > 0) {
                            "添加记忆需消耗 ${memoryCost}派币"
                        } else {
                            stringResource(R.string.group_chat_info_memory_cost)
                        },
                        style = TextStyle(
                            fontSize = 13.sp,
                            color = Color.Black
                        )
                    )
                }
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "🤖",
                        fontSize = 13.sp
                    )
                    Text(
                        text = stringResource(R.string.group_chat_info_memory_optimization),
                        style = TextStyle(
                            fontSize = 13.sp,
                            color = Color.Black
                        )
                    )
                }
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "✏️",
                        fontSize = 13.sp
                    )
                    Text(
                        text = stringResource(R.string.group_chat_info_memory_editable),
                        style = TextStyle(
                            fontSize = 13.sp,
                            color = Color.Black
                        )
                    )
                }
            }
            
            // 添加记忆按钮
            val isButtonEnabled = memoryText.isNotEmpty() && !viewModel.isAddingMemory
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
                    .clip(RoundedCornerShape(1000.dp))
                    .then(
                        if (isButtonEnabled) {
                            Modifier.background(
                                brush = Brush.horizontalGradient(
                                    colors = listOf(
                                        Color(0xFF7C45ED),
                                        Color(0x997C57EE),
                                        Color(0x887BD8F8)
                                    )
                                )
                            )
                        } else {
                            Modifier.background(
                                brush = Brush.horizontalGradient(
                                    colors = listOf(
                                        Color(0x337C45ED),
                                        Color(0x337C57EE),
                                        Color(0x337BD8F8)
                                    )
                                )
                            )
                        }
                    )
                    .noRippleClickable {
                        if (isButtonEnabled) {
                            onAddMemory(memoryText)
                        }
                    },
                contentAlignment = Alignment.Center
            ) {
                if (viewModel.isAddingMemory) {
                    androidx.compose.material3.CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = Color.White
                    )
                } else {
                    Text(
                        text = stringResource(R.string.group_chat_info_add_memory),
                        style = TextStyle(
                            fontSize = 17.sp,
                            color = if (isButtonEnabled) Color.White else Color.White.copy(alpha = 0.6f)
                        )
                    )
                }
            }
        }
    }
}

@Composable
fun GroupVisibilityDialog(
    viewModel: GroupChatInfoViewModel,
    onDismiss: () -> Unit,
    onConfirmPrivate: (Boolean) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val currentTrtcType = viewModel.groupInfo?.trtcType ?: "Public"
    val isPrivateFeePaid = viewModel.groupInfo?.privateFeePaid == true
    var isPrivate by remember { mutableStateOf(currentTrtcType == "Private") }
    val balance = viewModel.pointsBalance ?: 0
    val unlockCost = viewModel.privateGroupCost ?: 0
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .padding(bottom = 32.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 顶部标题
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(44.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Spacer(modifier = Modifier.width(24.dp))
            Text(
                text = stringResource(R.string.group_chat_info_permission_settings),
                style = TextStyle(
                    fontSize = 17.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.Black
                ),
                modifier = Modifier.weight(1f),
                textAlign = TextAlign.Center
            )
            Image(
                painter = painterResource(R.drawable.rider_pro_close),
                contentDescription = "关闭",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable { onDismiss() },
                colorFilter = ColorFilter.tint(Color.Black)
            )
        }
        
        Spacer(modifier = Modifier.height(6.dp))
        
        // 公开群组
        VisibilityOptionItem(
            title = stringResource(R.string.group_chat_info_public_group),
            desc = stringResource(R.string.group_chat_info_public_group_desc),
            badge = null,
            selected = !isPrivate,
            onClick = { isPrivate = false }
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 私密群组
        VisibilityOptionItem(
            title = stringResource(R.string.group_chat_info_private_group),
            desc = stringResource(R.string.group_chat_info_private_group_desc),
            badge = if (!isPrivateFeePaid && unlockCost > 0) "${unlockCost}派币" else null,
            selected = isPrivate,
            onClick = { isPrivate = true }
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 余额与费用（仅未解锁时显示）
        if (!isPrivateFeePaid) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = stringResource(R.string.group_chat_info_balance, balance),
                style = TextStyle(
                    fontSize = 13.sp,
                    color = Color(0x993C3C43)
                )
            )
            Text(
                text = stringResource(R.string.group_chat_info_unlock_cost, unlockCost),
                style = TextStyle(
                    fontSize = 13.sp,
                    color = Color(0xFF9284BD)
                )
            )
        }
        
        Spacer(modifier = Modifier.height(8.dp))
        }
        
        // 完成按钮
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .clip(RoundedCornerShape(1000.dp))
                .background(
                    brush = Brush.horizontalGradient(
                        colors = listOf(
                            Color(0xFF7C45ED),
                            Color(0xFF7C57EE),
                            Color(0xFF7BD8F8)
                        )
                    )
                )
                .noRippleClickable { 
                    onConfirmPrivate(isPrivate)
                },
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = stringResource(R.string.group_chat_info_done),
                style = TextStyle(fontSize = 17.sp, color = Color.White)
            )
        }
        
        // 仅未解锁时显示充值提示
        if (!isPrivateFeePaid) {
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = stringResource(R.string.group_chat_info_recharge_hint),
            style = TextStyle(fontSize = 12.sp, color = Color(0x4D3C3C43)),
            textAlign = TextAlign.Center
        )
        }
    }
}

@Composable
private fun VisibilityOptionItem(
    title: String,
    desc: String,
    badge: String?,
    selected: Boolean,
    onClick: () -> Unit
) {
    val borderColor = Color(0x1F7D767F)
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(68.dp)
            .clip(RoundedCornerShape(16.dp))
            .background(Color.White)
            .padding(horizontal = 12.dp)
            .noRippleClickable { onClick() },
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Box(
                modifier = Modifier
                    .size(32.dp)
                    .clip(RoundedCornerShape(10.dp))
                    .background(Color(0x0F7C45ED)),
                contentAlignment = Alignment.Center
            ) {
                Text(text = if (title.contains("私密")) "🔒" else "🌐", fontSize = 16.sp)
            }
            Spacer(modifier = Modifier.width(10.dp))
            Column(modifier = Modifier.widthIn(max = 240.dp)) {
                Text(text = title, style = TextStyle(fontSize = 15.sp, color = Color.Black))
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = desc,
                    style = TextStyle(fontSize = 12.sp, color = Color(0x993C3C43))
                )
            }
        }
        Spacer(modifier = Modifier.weight(1f))
        Row(verticalAlignment = Alignment.CenterVertically) {
            if (badge != null) {
                Box(
                    modifier = Modifier
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color(0x1AFEBC2F))
                        .padding(horizontal = 10.dp, vertical = 4.dp)
                ) {
                    Text(
                        text = badge,
                        style = TextStyle(fontSize = 15.sp, color = Color(0xFF008D28))
                    )
                }
                Spacer(modifier = Modifier.width(8.dp))
            }
            if (selected) {
                Box(
                    modifier = Modifier
                        .size(22.dp)
                        .clip(CircleShape)
                        .background(Color(0xFF34C759)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(text = "✓", color = Color.White, fontSize = 14.sp)
                }
            }
        }
    }
}
