package com.aiosman.ravenow.ui.index.tabs.profile

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
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.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Text
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
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.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.MainActivity
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.PointService
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.pickupAndCompressLauncher
import com.aiosman.ravenow.ui.index.IndexViewModel
import com.aiosman.ravenow.ui.index.tabs.profile.composable.GalleryGrid
import com.aiosman.ravenow.ui.index.tabs.profile.composable.GroupChatEmptyContent
import com.aiosman.ravenow.ui.index.tabs.profile.composable.OtherProfileAction
import com.aiosman.ravenow.ui.index.tabs.profile.composable.UserAgentsList
import com.aiosman.ravenow.ui.index.tabs.profile.composable.UserAgentsRow
import com.aiosman.ravenow.ui.index.tabs.profile.composable.UserContentPageIndicator
import com.aiosman.ravenow.ui.index.tabs.profile.composable.UserItem
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.post.MenuActionItem
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.text.NumberFormat
import java.util.Locale
import kotlin.math.max

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class)
@Composable
fun ProfileV3(
    onUpdateBanner: ((Uri, File, Context) -> Unit)? = null,
    profile: AccountProfileEntity? = null,
    onLogout: () -> Unit = {},
    onFollowClick: () -> Unit = {},
    onChatClick: () -> Unit = {},
    moments: List<MomentEntity>,
    agents: List<AgentEntity> = emptyList(),
    isSelf: Boolean = true,
    isMain:Boolean = false,
    isAiAccount: Boolean = false, // 新增参数判断是否为AI账户
    onLoadMore: () -> Unit = {},
    onLike: (MomentEntity) -> Unit = {},
    onComment: (MomentEntity) -> Unit = {},
    onAgentClick: (AgentEntity) -> Unit = {},
    postCount: Long? = null, // 新增参数用于传递帖子总数
) {
    val model = MyProfileViewModel
    // Tabs: 动态、(可选)智能体、群聊
    val pagerState = rememberPagerState(
        initialPage = model.profileCurrentPage,
        pageCount = { if (isAiAccount) 2 else 3 }
    )
    val enabled by remember { mutableStateOf(true) }
    val statusBarPaddingValues = WindowInsets.systemBars.asPaddingValues()
    var expanded by remember { mutableStateOf(false) }
    var minibarExpanded by remember { mutableStateOf(false) }
    var showAgentMenu by remember { mutableStateOf(false) }
    var contextAgent by remember { mutableStateOf<AgentEntity?>(null) }
    var showDeleteConfirmDialog by remember { mutableStateOf(false) }
    var showOtherUserMenu by remember { mutableStateOf(false) }
    var showBlockConfirmDialog by remember { mutableStateOf(false) }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    val bannerWidth = 402
    val bannerHeight = 206
    val pickBannerImageLauncher = pickupAndCompressLauncher(
        context,
        scope,
        maxSize = ConstVars.BANNER_IMAGE_MAX_SIZE,
        quality = 100
    ) { uri, file ->
        onUpdateBanner?.invoke(uri, file, context)
    }
    val refreshState = rememberPullRefreshState(model.refreshing, onRefresh = {
        model.loadProfile(pullRefresh = true)
    })
    val agentMenuModalState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    var miniToolbarHeight by remember { mutableStateOf(0) }
    val density = LocalDensity.current
    val appTheme = LocalAppTheme.current
    val AppColors = appTheme
    val systemUiController = rememberSystemUiController()
    val listState = rememberLazyListState(
        initialFirstVisibleItemIndex = model.profileAgentListFirstVisibleItemIndex,
        initialFirstVisibleItemScrollOffset = model.profileAgentListFirstVisibleItemOffset
    )
    val groupChatListState = rememberLazyListState(
        initialFirstVisibleItemIndex = model.profileGroupChatFirstVisibleItemIndex,
        initialFirstVisibleItemScrollOffset = model.profileGroupChatFirstVisibleItemOffset
    )
    val gridState = rememberLazyGridState(
        initialFirstVisibleItemIndex = model.profileGridFirstVisibleItemIndex,
        initialFirstVisibleItemScrollOffset = model.profileGridFirstVisibleItemOffset
    )
    val scrollState = rememberScrollState(model.profileScrollOffset)
    val nestedScrollConnection = remember(scrollState, pagerState, gridState, listState, groupChatListState, isAiAccount) {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                if (available.y >= 0f) return Offset.Zero
                val consumed = scrollState.dispatchRawDelta(-available.y)
                return if (consumed != 0f) Offset(0f, -consumed) else Offset.Zero
            }

            override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
                if (available.y <= 0f) return Offset.Zero

                val childCanScrollUp = when (pagerState.currentPage) {
                    0 -> gridState.firstVisibleItemIndex > 0 || gridState.firstVisibleItemScrollOffset > 0
                    1 -> if (!isAiAccount) {
                        listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0
                    } else {
                        groupChatListState.firstVisibleItemIndex > 0 || groupChatListState.firstVisibleItemScrollOffset > 0
                    }
                    2 -> if (!isAiAccount) {
                        groupChatListState.firstVisibleItemIndex > 0 || groupChatListState.firstVisibleItemScrollOffset > 0
                    } else {
                        false
                    }
                    else -> false
                }
                if (childCanScrollUp) return Offset.Zero

                val consumedByParent = scrollState.dispatchRawDelta(-available.y)
                return if (consumedByParent != 0f) Offset(0f, -consumedByParent) else Offset.Zero
            }
        }
    }
    LaunchedEffect(pagerState.currentPage) {
        model.profileCurrentPage = pagerState.currentPage
    }
    DisposableEffect(Unit) {
        onDispose {
            model.profileScrollOffset = scrollState.value
            model.profileGridFirstVisibleItemIndex = gridState.firstVisibleItemIndex
            model.profileGridFirstVisibleItemOffset = gridState.firstVisibleItemScrollOffset
            model.profileAgentListFirstVisibleItemIndex = listState.firstVisibleItemIndex
            model.profileAgentListFirstVisibleItemOffset = listState.firstVisibleItemScrollOffset
            model.profileGroupChatFirstVisibleItemIndex = groupChatListState.firstVisibleItemIndex
            model.profileGroupChatFirstVisibleItemOffset = groupChatListState.firstVisibleItemScrollOffset
        }
    }
    val pointsBalanceState = PointService.pointsBalance.collectAsState(initial = null)

    // 计算导航栏背景透明度，根据滚动位置从0到1，在前段就达到完全不透明
    val toolbarBackgroundAlpha by remember {
        derivedStateOf {
            val maxScroll = 120f // 大幅减少最大滚动距离，让前段就完全不透明
            val progress = (scrollState.value.coerceAtMost(maxScroll.toInt()) / maxScroll).coerceIn(0f, 1f)
            // 直接使用线性插值，尽快达到完全不透明
            progress
        }
    }

    // observe list scrolling
    val reachedAgentsBottom by remember {
        derivedStateOf {
            if (isAiAccount || pagerState.currentPage != 1) {
                false
            } else {
                val layoutInfo = listState.layoutInfo
                val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
                val totalItems = layoutInfo.totalItemsCount
                if (lastVisibleItem == null || totalItems == 0) {
                    false
                } else {
                    val triggerIndex = max(0, totalItems - 2)
                    lastVisibleItem.index >= triggerIndex && model.agentLoader.hasNext && !model.agentLoader.isLoading
                }
            }
        }
    }

    // observe grid scrolling for load more
    val reachedGridBottom by remember {
        derivedStateOf {
            val layoutInfo = gridState.layoutInfo
            val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
            val totalItems = layoutInfo.totalItemsCount
            val visibleItemsCount = layoutInfo.visibleItemsInfo.size

            Log.d("ProfileV3", "滚动状态检查 - totalItems: $totalItems, visibleItems: $visibleItemsCount, lastVisibleIndex: ${lastVisibleItem?.index}, moments.size: ${moments.size}, hasNext: ${model.momentLoader.hasNext}")

            // 如果没有可见item，不触发加载
            if (lastVisibleItem == null || totalItems == 0) {
                Log.d("ProfileV3", "跳过加载 - 没有可见item或总数为0")
                false
            } else {
                // 检查是否滚动到最后几个item（考虑到有Spacer item）
                // 当接近底部时提前触发加载
                val triggerIndex = maxOf(0, totalItems - 2)
                val result = lastVisibleItem.index >= triggerIndex && model.momentLoader.hasNext
                Log.d("ProfileV3", "滚动检测结果 - lastVisibleIndex: ${lastVisibleItem.index}, triggerIndex: $triggerIndex, hasNext: ${model.momentLoader.hasNext}, shouldTrigger: $result")
                result
            }
        }
    }

    // load more if scrolled to bottom of list
    LaunchedEffect(reachedAgentsBottom) {
        if (reachedAgentsBottom) {
            model.loadMoreAgent()
        }
    }

    // load more if scrolled to bottom of grid
    LaunchedEffect(reachedGridBottom) {
        Log.d("ProfileV3", "LaunchedEffect触发 - reachedGridBottom: $reachedGridBottom")
        if (reachedGridBottom) {
            Log.d("ProfileV3", "检测到网格滚动到底部，触发加载更多")
            onLoadMore()
        }
    }

    fun switchTheme() {
        // delay
        scope.launch {
            delay(200)
            AppState.switchTheme()
            systemUiController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
            if (AppState.darkMode) {
                (context as MainActivity).window.decorView.setBackgroundColor(android.graphics.Color.BLACK)
            } else {
                (context as MainActivity).window.decorView.setBackgroundColor(android.graphics.Color.WHITE)
            }
        }

    }

    // Agent菜单弹窗
    if (showAgentMenu) {
        Log.d("ProfileV3", "Showing agent menu for: ${contextAgent?.title}")
        ModalBottomSheet(
            onDismissRequest = {
                showAgentMenu = false
            },
            containerColor = AppColors.background,
            sheetState = agentMenuModalState,
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        ) {
            AgentMenuModal(
                agent = contextAgent,
                onDeleteClick = {
                    scope.launch {
                        agentMenuModalState.hide()
                        showAgentMenu = false
                        showDeleteConfirmDialog = true
                    }
                },
                onCloseClick = {
                    scope.launch {
                        agentMenuModalState.hide()
                        showAgentMenu = false
                    }
                },
                isSelf = isSelf
            )
        }
    }

    // 删除确认对话框
    if (showDeleteConfirmDialog) {
        DeleteConfirmDialog(
            agentName = contextAgent?.title ?: "",
            onConfirm = {
                // TODO: 实现删除逻辑
                contextAgent?.let { agent ->
                    // 调用删除API
                    scope.launch {
                        try {
                            // 这里应该调用删除智能体的API
                            // agentService.deleteAgent(agent.id)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
                showDeleteConfirmDialog = false
                contextAgent = null
            },
            onDismiss = {
                showDeleteConfirmDialog = false
                contextAgent = null
            }
        )
    }

    Box(
        modifier = Modifier.pullRefresh(refreshState)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(scrollState)
                .background(AppColors.profileBackground)
        ) {
            // Banner
            val banner = profile?.banner
            if (banner != null) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(bannerHeight.dp)
                        .background(AppColors.profileBackground),
                    contentAlignment = Alignment.Center
                ) {
                    Box(
                        modifier = Modifier
                            .width(bannerWidth.dp)
                            .height(bannerHeight.dp)
                            .clip(
                                RoundedCornerShape(
                                    bottomStart = 32.dp,
                                    bottomEnd = 32.dp
                                )
                            )
                    ) {
                        CustomAsyncImage(
                            LocalContext.current,
                            banner,
                            modifier = Modifier.fillMaxSize(),
                            contentDescription = "",
                            contentScale = ContentScale.Crop
                        )
                    }
                }
            } else {
                Spacer(modifier = Modifier.height(100.dp))
            }

            // 壁纸下方间距

            // 用户信息
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(AppColors.profileBackground)
                    .padding(horizontal = 16.dp)
            ) {
                profile?.let {
                    UserItem(
                        accountProfileEntity = it,
                        postCount = postCount ?: if (isSelf) MyProfileViewModel.momentLoader.total else moments.size.toLong(),
                        isSelf = isSelf,
                        onEditClick = {
                            navController.navigate(NavigationRoute.AccountEdit.route)
                        }
                    )
                }
            }

            Spacer(modifier = Modifier.height(20.dp))

            // 操作按钮（仅其他用户显示）
            profile?.let {
                if (!isSelf && it.id != AppState.UserId) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp)
                    ) {
                        OtherProfileAction(
                            it,
                            onFollow = {
                                onFollowClick()
                            },
                            onChat = {
                                onChatClick()
                            }
                        )
                    }
                }
            }

            // 用户智能体行
            if (!isAiAccount) {
                UserAgentsRow(
                    userId = if (isSelf) null else profile?.id,
                    modifier = Modifier.padding(top = 16.dp),
                    onMoreClick = {
                        // 导航到智能体列表页面
                    },
                    onAgentClick = { agent ->
                        // 导航到智能体详情页面
                    },
                    onAvatarClick = { agent ->
                        // 导航到智能体个人主页
                        scope.launch {
                            try {
                                val userService = com.aiosman.ravenow.data.UserServiceImpl()
                                val profile = userService.getUserProfileByOpenId(agent.openId)
                                navController.navigate(
                                    NavigationRoute.AccountProfile.route
                                        .replace("{id}", profile.id.toString())
                                        .replace("{isAiAccount}", "true")
                                )
                            } catch (e: Exception) {
                                // 处理错误
                            }
                        }
                    },
                    onAgentLongClick = { agent ->
                        Log.d("ProfileV3", "onAgentLongClick called for agent: ${agent.title}, isSelf: $isSelf")
                        if (isSelf) { // 只有自己的智能体才能长按
                            Log.d("ProfileV3", "Setting contextAgent and showing menu")
                            contextAgent = agent
                            showAgentMenu = true
                        }
                    }
                )
            }

            // 内容
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(AppColors.profileBackground)
                    .padding(top = 8.dp)
            ) {
                UserContentPageIndicator(
                    pagerState = pagerState,
                    showAgentTab = !isAiAccount
                )
                HorizontalPager(
                    state = pagerState,
                    modifier = Modifier.height(650.dp) // 固定滚动高度
                ) { idx ->
                    when (idx) {
                        0 -> GalleryGrid(
                            moments = moments,
                            modifier = Modifier.fillMaxSize(),
                            state = gridState,
                            nestedScrollConnection = nestedScrollConnection
                        )
                        1 -> {
                            if (!isAiAccount) {
                                UserAgentsList(
                                    agents = agents,
                                    onAgentClick = onAgentClick,
                                    onAvatarClick = { agent ->
                                        // 导航到智能体个人主页，需要通过openId获取用户ID
                                        scope.launch {
                                            try {
                                                val userService = com.aiosman.ravenow.data.UserServiceImpl()
                                                val profile = userService.getUserProfileByOpenId(agent.openId)
                                                navController.navigate(
                                                    NavigationRoute.AccountProfile.route
                                                        .replace("{id}", profile.id.toString())
                                                        .replace("{isAiAccount}", "true")
                                                )
                                            } catch (e: Exception) {
                                                // 处理错误
                                            }
                                        }
                                    },
                                    hasMore = model.agentLoader.hasNext,
                                    isLoading = model.agentLoader.isLoading,
                                    showNoMoreText = isSelf,
                                    modifier = Modifier.fillMaxSize(),
                                    state = listState,
                                    nestedScrollConnection = nestedScrollConnection,
                                    showSegments = isSelf // 只有查看自己的主页时才显示分段控制器
                                )
                            } else {
                                // 查看其他用户的主页时，传递该用户的chatAIId以显示其创建的群聊；查看自己的主页时传递null
                                GroupChatPlaceholder(
                                    modifier = Modifier.fillMaxSize(),
                                    listState = groupChatListState,
                                    nestedScrollConnection = nestedScrollConnection,
                                    ownerSessionId = if (!isSelf) profile?.chatAIId else null,
                                    showSegments = isSelf // 只有查看自己的主页时才显示分段控制器
                                )
                            }
                        }
                        2 -> {
                            if (!isAiAccount) {
                                // 查看其他用户的主页时，传递该用户的chatAIId以显示其创建的群聊；查看自己的主页时传递null
                                GroupChatPlaceholder(
                                    modifier = Modifier.fillMaxSize(),
                                    listState = groupChatListState,
                                    nestedScrollConnection = nestedScrollConnection,
                                    ownerSessionId = if (!isSelf) profile?.chatAIId else null,
                                    showSegments = isSelf // 只有查看自己的主页时才显示分段控制器
                                )
                            }
                        }
                    }
                }
            }
            
            // 底部间距，增加滚动距离
            Spacer(modifier = Modifier.height(16.dp))
        }

        // 顶部导航栏
        TopNavigationBar(
            isMain = isMain,
            isSelf = isSelf,
            profile = profile,
            navController = navController,
            backgroundAlpha = toolbarBackgroundAlpha,
            interactionCount = moments.sumOf { it.likeCount }, // 计算总点赞数作为互动数据
            onPointsClick = {
                if (isSelf) com.aiosman.ravenow.ui.points.PointsSheetManager.open()
            },
            onMenuClick = {
                showOtherUserMenu = true
            },
            onShareClick = {
                // TODO: 实现分享功能
            }
        )

        PullRefreshIndicator(
            model.refreshing,
            refreshState,
            Modifier.align(Alignment.TopCenter)
        )
        
        // 其他用户菜单弹窗
        if (showOtherUserMenu) {
            ModalBottomSheet(
                onDismissRequest = { showOtherUserMenu = false },
                sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
                containerColor = Color.Transparent, // 设置容器背景透明
                contentColor = Color.Transparent, // 设置内容背景透明
                dragHandle = null, // 移除拖拽手柄
                contentWindowInsets = {androidx.compose.foundation.layout.WindowInsets(0)},
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.Transparent)
                ) {
                OtherUserMenuModal(
                    onBlockClick = {
                        showBlockConfirmDialog = true
                    },
                        onReportClick = {
                            // 实现举报逻辑
                        },
                        onCancelClick = {
                            showOtherUserMenu = false
                        },
                    onDismiss = { showOtherUserMenu = false }
                )
            }
        }

        // 拉黑确认弹窗
        if (showBlockConfirmDialog) {
            ModalBottomSheet(
                onDismissRequest = {
                    showBlockConfirmDialog = false
                },
                sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
                containerColor = Color.Transparent,
                contentColor = Color.Transparent,
                dragHandle = null,
                contentWindowInsets = { androidx.compose.foundation.layout.WindowInsets(0) }
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.Transparent)
                ) {
                    BlockConfirmDialog(
                        userProfile = profile,
                        onConfirmBlock = {
                            // 实现拉黑逻辑
                        },
                        onDismiss = {
                            showBlockConfirmDialog = false
                            showOtherUserMenu = false
                        }
                    )
                }
            }
        }

        // 积分底部弹窗
        // 全局积分弹窗由 MainActivity 中的 PointsBottomSheetHost 承载
    }
}
}

@Composable
private fun GroupChatPlaceholder(
    modifier: Modifier = Modifier,
    listState: androidx.compose.foundation.lazy.LazyListState,
    nestedScrollConnection: NestedScrollConnection? = null,
    ownerSessionId: String? = null, // 创建者用户ID（ChatAIID），用于过滤特定创建者的房间。如果为null，则显示当前用户创建或加入的房间
    showSegments: Boolean = true // 是否显示分段控制器（全部、公开、私有）
) {
    GroupChatEmptyContent(
        modifier = modifier,
        listState = listState,
        nestedScrollConnection = nestedScrollConnection,
        ownerSessionId = ownerSessionId,
        showSegments = showSegments
    )
}

//顶部导航栏组件
@Composable
fun TopNavigationBar(
    isMain: Boolean,
    isSelf: Boolean,
    profile: AccountProfileEntity?,
    navController: androidx.navigation.NavController,
    backgroundAlpha: Float,
    interactionCount: Int = 0,
    onPointsClick: (() -> Unit)? = null,
    onMenuClick: () -> Unit = {},
    onShareClick: () -> Unit = {}
) {
    val appColors = LocalAppTheme.current
    val numberFormat = remember { NumberFormat.getNumberInstance(Locale.getDefault()) }
    // 仅本人主页显示积分：收集全局积分
    val pointsBalanceState = if (isSelf) PointService.pointsBalance.collectAsState(initial = null) else null
    
    // 响应式监听暗色模式变化 - 通过 LocalAppTheme 的变化来触发重组
    // 当 AppState.darkMode 改变时，AppState.appTheme 也会改变，从而触发 LocalAppTheme 更新
    val darkMode = AppState.darkMode
    
    // 根据背景透明度和暗色模式决定图标颜色
    // 暗色模式下：图标始终为白色
    // 亮色模式下：根据背景透明度决定，透明度为1时变黑，否则为白色
    val iconColor = remember(darkMode, backgroundAlpha) {
        if (darkMode) {
            Color.White // 暗色模式下图标始终为白色
        } else {
            if (backgroundAlpha >= 1f) Color.Black else Color.White
        }
    }
    val cardBorderColor = remember(darkMode, backgroundAlpha) {
        if (darkMode) {
            Color.White.copy(alpha = 0.35f) // 暗色模式下使用半透明白色，避免整体变白
        } else {
            if (backgroundAlpha >= 1f) Color.Black else Color.White
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        val statusBarPadding = WindowInsets.systemBars.asPaddingValues()
        val statusBarHeight = statusBarPadding.calculateTopPadding()
        val navigationBarHeight = 56.dp // 增加导航栏高度，包括图标和额外空间
        
        // 导航栏背景层，包括状态栏区域，根据滚动位置逐渐显示实色填充
        val totalHeight = statusBarHeight + navigationBarHeight
        
        // 根据滚动位置计算背景颜色，从透明逐渐变为实色填充，尽快完成
        val toolbarBackgroundColor = remember(backgroundAlpha, darkMode) {
            val progress = backgroundAlpha.coerceIn(0f, 1f)
            
            if (darkMode) {
                // 暗色模式下：从透明逐渐变为黑色实色填充
                Color.Black.copy(alpha = progress)
            } else {
                // 亮色模式下：从透明逐渐变为白色实色填充
                Color.White.copy(alpha = progress)
            }
        }
        
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(totalHeight) // 状态栏高度 + 导航栏高度
                .align(Alignment.TopCenter)
                .background(
                    color = toolbarBackgroundColor // 实色填充，不使用渐变
                )
        )
        
        // 功能按钮区域，图标和文字根据背景透明度改变颜色
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp, bottom = 16.dp, end = 16.dp) // 增加上下内边距
                .align(Alignment.TopEnd)
                .padding(top = statusBarHeight), // 从状态栏下方开始
            horizontalArrangement = Arrangement.End,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧：互动数据卡片（仅自己的界面显示）
            if (isSelf) {
                // 根据 toolbar 背景透明度动态调整卡片背景
                val cardBackgroundColor = remember(backgroundAlpha, darkMode) {
                    val smoothProgress = backgroundAlpha.coerceIn(0f, 1f)
                    if (darkMode) {
                        // 暗色模式：保持在半透明灰白区间，避免滚动到顶部后变纯白
                        val minAlpha = 0.18f
                        val maxAlpha = 0.35f
                        val alpha = minAlpha + (maxAlpha - minAlpha) * smoothProgress
                        Color.White.copy(alpha = alpha)
                    } else {
                        // 亮色模式：从半透明白色逐渐变为完全不透明的白色
                        Color.White.copy(alpha = 0.52f + (0.48f * smoothProgress))
                    }
                }
                
                Row(
                    modifier = Modifier
                        .height(24.dp)
                        .background(
                            color = cardBackgroundColor,
                            shape = RoundedCornerShape(16.dp)
                        )
                        .border(
                            width = 0.5.dp,
                            color = cardBorderColor, // 根据背景透明度改变边框颜色
                            shape = RoundedCornerShape(16.dp)
                        )
                        .padding(horizontal = 8.dp)
                        .noRippleClickable { onPointsClick?.invoke() },
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    // 互动图标
                    Image(
                        painter = painterResource(id = R.mipmap.paip_coin_img),
                        contentDescription = "互动",
                        modifier = Modifier.size(24.dp),
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = pointsBalanceState?.value?.balance?.let { numberFormat.format(it) } ?: "--",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.W500,
                        color = remember(darkMode) { if (darkMode) Color.White else Color.Black }, // 暗色模式下为白色，亮色模式下为黑色
                        textAlign = TextAlign.Center
                    )
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                // 中间：分享图标（仅自己的界面显示）
                Image(
                    painter = painterResource(id = R.mipmap.menu_icon),
                    contentDescription = "分享",
                    modifier = Modifier
                        .size(24.dp)
                        .noRippleClickable {
                            onShareClick()
                        },
                    colorFilter = ColorFilter.tint(iconColor) // 根据背景透明度改变颜色
                )
                
                Spacer(modifier = Modifier.width(16.dp))
            }
            
            // 右侧：菜单图标（三点图标）
            Image(
                painter = painterResource(id = R.drawable.rider_pro_more_horizon),
                contentDescription = "菜单",
                modifier = Modifier
                    .size(24.dp)
                    .noRippleClickable {
                        if (isSelf && isMain) {
                            IndexViewModel.openDrawer = true
                        } else {
                            onMenuClick()
                        }
                    },
                colorFilter = ColorFilter.tint(iconColor) // 根据背景透明度改变颜色
            )
        }
        
        // 如果不是主页面，显示返回按钮和用户信息
        if (!isMain) {
            val statusBarPadding = WindowInsets.systemBars.asPaddingValues()
            // 判断是否有背景图
            val hasBanner = profile?.banner != null
            
            Row(
                modifier = Modifier
                    .align(Alignment.TopStart)
                    .padding(horizontal = 16.dp, vertical = 8.dp)
                    .padding(top = statusBarPadding.calculateTopPadding()),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 返回按钮：深色模式下为白色，亮色模式下为黑色
                val backButtonColor = remember(darkMode) { if (darkMode) Color.White else Color.Black }
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_back_icon),
                    contentDescription = "Back",
                    modifier = Modifier
                        .noRippleClickable {
                            navController.navigateUp()
                        }
                        .size(24.dp),
                    colorFilter = ColorFilter.tint(backButtonColor) // 深色模式下为白色，亮色模式下为黑色
                )
                
                // 未设置背景的用户（自己的主页且没有背景图）显示昵称
                if (isSelf && !hasBanner && profile != null) {
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = profile.nickName ?: "",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W600,
                        color = backButtonColor // 深色模式下为白色，亮色模式下为黑色
                    )
                }
            }
        }
    }
}

// 分享图标（向上箭头）
@Composable
fun ShareIcon(
    color: Color,
    modifier: Modifier = Modifier
) {
    Canvas(modifier = modifier) {
        val strokeWidth = 2.dp.toPx()
        val centerX = size.width / 2
        val centerY = size.height / 2
        
        // 绘制向上的箭头
        // 底部横线
        drawLine(
            color = color,
            start = Offset(centerX - 9.dp.toPx(), centerY + 6.dp.toPx()),
            end = Offset(centerX + 9.dp.toPx(), centerY + 6.dp.toPx()),
            strokeWidth = strokeWidth
        )
        // 顶部横线
        drawLine(
            color = color,
            start = Offset(centerX - 5.dp.toPx(), centerY - 6.5.dp.toPx()),
            end = Offset(centerX + 5.dp.toPx(), centerY - 6.5.dp.toPx()),
            strokeWidth = strokeWidth
        )
        // 中间竖线
        drawLine(
            color = color,
            start = Offset(centerX, centerY - 3.dp.toPx()),
            end = Offset(centerX, centerY + 6.dp.toPx()),
            strokeWidth = strokeWidth
        )
    }
}

// 菜单图标（三条横线）
@Composable
fun MenuIcon(
    color: Color,
    modifier: Modifier = Modifier
) {
    Canvas(modifier = modifier) {
        val strokeWidth = 2.dp.toPx()
        val centerX = size.width / 2
        val centerY = size.height / 2
        val lineLength = 16.dp.toPx()
        val spacing = 6.dp.toPx()
        
        // 绘制三条横线
        drawLine(
            color = color,
            start = Offset(centerX - lineLength / 2, centerY - spacing),
            end = Offset(centerX + lineLength / 2, centerY - spacing),
            strokeWidth = strokeWidth
        )
        drawLine(
            color = color,
            start = Offset(centerX - lineLength / 2, centerY),
            end = Offset(centerX + lineLength / 2, centerY),
            strokeWidth = strokeWidth
        )
        drawLine(
            color = color,
            start = Offset(centerX - lineLength / 2, centerY + spacing),
            end = Offset(centerX + lineLength / 2, centerY + spacing),
            strokeWidth = strokeWidth
        )
    }
}

/**
 * Agent菜单弹窗
 */
@Composable
fun AgentMenuModal(
    agent: AgentEntity?,
    onDeleteClick: () -> Unit = {},
    onCloseClick: () -> Unit = {},
    isSelf: Boolean = true
) {
    val AppColors = LocalAppTheme.current
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(AppColors.background)
            .padding(vertical = 24.dp, horizontal = 20.dp)
    ) {
        Text(
            "智能体",
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = AppColors.text
        )
        Spacer(modifier = Modifier.height(24.dp))
        
        agent?.let {
            Column(
                modifier = Modifier
                    .clip(RoundedCornerShape(8.dp))
                    .background(AppColors.nonActive)
                    .padding(8.dp)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Box(
                        modifier = Modifier
                            .size(24.dp)
                            .clip(CircleShape)
                    ) {
                        CustomAsyncImage(
                            context = LocalContext.current,
                            imageUrl = it.avatar,
                            modifier = Modifier.fillMaxSize(),
                            contentDescription = "Avatar",
                            defaultRes = R.mipmap.rider_pro_agent
                        )
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        it.title,
                        fontWeight = FontWeight.Bold,
                        fontSize = 16.sp,
                        color = AppColors.text
                    )
                }
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    it.desc.ifEmpty { "暂无描述" },
                    maxLines = 2,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 32.dp),
                    overflow = TextOverflow.Ellipsis,
                    color = AppColors.text,
                    fontSize = 14.sp
                )
            }
            Spacer(modifier = Modifier.height(32.dp))
        }

        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (isSelf) {
                MenuActionItem(
                    icon = R.drawable.rider_pro_moment_delete,
                    text = stringResource(R.string.delete)
                ) {
                    onDeleteClick()
                }
                Spacer(modifier = Modifier.width(48.dp))
            }
            
            MenuActionItem(
                icon = R.drawable.rider_pro_more_horizon,
                text = "更多"
            ) {
                // TODO: 实现更多功能
                onCloseClick()
            }
        }
        Spacer(modifier = Modifier.height(48.dp))
    }
}



/**
 * 删除确认对话框
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeleteConfirmDialog(
    agentName: String,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    val AppColors = LocalAppTheme.current
    
    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "确认删除",
                color = AppColors.text,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Text(
                text = "确定要删除智能体「$agentName」吗？删除后无法恢复。",
                color = AppColors.text,
                fontSize = 14.sp
            )
        },
        confirmButton = {
            androidx.compose.material3.TextButton(
                onClick = {
                    onConfirm()
                }
            ) {
                Text(
                    "删除",
                    color = AppColors.error,
                    fontWeight = FontWeight.Bold
                )
            }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(
                onClick = onDismiss
            ) {
                Text(
                    "取消",
                    color = AppColors.text
                )
            }
        },
        containerColor = AppColors.background
    )
}

/**
 * 其他用户主页菜单弹窗
 */
@Composable
fun OtherUserMenuModal(
    onBlockClick: () -> Unit = {},
    onReportClick: () -> Unit = {},
    onCancelClick: () -> Unit = {},
    onDismiss: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.BottomCenter
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp)
                .padding(bottom = 11.dp)
        ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    color = AppColors.background,
                    shape = RoundedCornerShape(8.dp)
                )
        ) {
            // 拉黑选项
            androidx.compose.material3.TextButton(
                onClick = {
                    onBlockClick()
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    stringResource(R.string.block),
                    color = AppColors.error,
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp
                )
            }
            
            // 分割线
            androidx.compose.material3.HorizontalDivider(
                color = AppColors.divider,
                thickness = 0.5.dp
            )
            
            // 举报选项
            androidx.compose.material3.TextButton(
                onClick = {
                    onReportClick()
                    onDismiss()
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    stringResource(R.string.report),
                    color = AppColors.error,
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp
                )
            }
        }
        
        Spacer(modifier = Modifier.height(8.dp))
        
        // 取消按钮
        androidx.compose.material3.TextButton(
            onClick = {
                onCancelClick()
                onDismiss()
            },
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    color = AppColors.background,
                    shape = RoundedCornerShape(8.dp)
                )
        ) {
            Text(
                stringResource(R.string.cancel),
                color = AppColors.text,
                fontSize = 16.sp
            )
        }
        }
    }
}
