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

import android.annotation.SuppressLint
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.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.navigationBars
import androidx.compose.foundation.layout.offset
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.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
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.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
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 androidx.navigation.NavHostController
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.index.tabs.ai.tabs.mine.MineAgent
import com.aiosman.ravenow.ui.index.tabs.ai.tabs.hot.HotAgent
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.composables.TabItem
import com.aiosman.ravenow.ui.composables.TabSpacer
import com.aiosman.ravenow.ui.index.tabs.moment.CustomTabItem
import com.aiosman.ravenow.ui.index.tabs.moment.tabs.expolre.AgentItem
import com.aiosman.ravenow.ui.index.tabs.moment.tabs.expolre.ExploreViewModel
import com.aiosman.ravenow.utils.DebounceUtils
import com.aiosman.ravenow.utils.ResourceCleanupManager
import kotlinx.coroutines.launch
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.foundation.lazy.grid.items as gridItems
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Brush
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.ui.platform.LocalConfiguration
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition

// 检测是否接近列表底部的扩展函数
fun LazyListState.isScrolledToEnd(buffer: Int = 3): Boolean {
    val layoutInfo = this.layoutInfo
    val totalItemsCount = layoutInfo.totalItemsCount
    val lastVisibleItemIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0

    return lastVisibleItemIndex >= (totalItemsCount - buffer)
}

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun Agent() {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 48.dp
    val statusBarPaddingValues = WindowInsets.systemBars.asPaddingValues()
    // 游客模式下只显示热门Agent，正常用户显示我的Agent和热门Agent
    val tabCount = if (AppStore.isGuest) 1 else 2
    var pagerState = rememberPagerState { tabCount }
    var scope = rememberCoroutineScope()

    val viewModel: AgentViewModel = AgentViewModel

    // 确保推荐Agent数据已加载
    LaunchedEffect(Unit) {
        viewModel.ensureDataLoaded()
    }

    // 防抖状态
    var lastClickTime by remember { mutableStateOf(0L) }

    // 页面退出时只清理必要的资源，不清理推荐Agent数据
    DisposableEffect(Unit) {
        onDispose {
            // 只清理子页面的资源，保留推荐Agent数据
            // ResourceCleanupManager.cleanupPageResources("ai")
        }
    }

    val agentItems = viewModel.agentItems
    var selectedTabIndex by remember { mutableStateOf(0) }

    // 无限滚动状态
    val listState = rememberLazyListState()

    // 创建一个可观察的滚动到底部状态
    val isScrolledToEnd by remember {
        derivedStateOf {
            listState.isScrolledToEnd()
        }
    }

    // 检测滚动到底部并加载更多数据
    LaunchedEffect(isScrolledToEnd) {
        if (isScrolledToEnd && !viewModel.isLoadingMore && agentItems.isNotEmpty() && viewModel.hasMoreData) {
            viewModel.loadMoreAgents()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Image(
                        painter = painterResource(id = R.drawable.home_logo),
                        contentDescription = "Rave AI Logo",
                        modifier = Modifier
                            .height(44.dp)
                            .padding(top =9.dp,bottom=9.dp)
                            .wrapContentSize(),
//                        colorFilter = ColorFilter.tint(AppColors.text)
                    )
                },
                actions = {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_nav_search),
                        contentDescription = "search",
                        modifier = Modifier
                            .size(44.dp)
                            .padding(top = 9.dp,bottom=9.dp)
                            .noRippleClickable {
                                navController.navigate(NavigationRoute.Search.route)
                            },
                        colorFilter = ColorFilter.tint(AppColors.text)
                    )
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = AppColors.background
                ),
                windowInsets = WindowInsets(0, 0, 0, 0),
                modifier = Modifier
                    .height(44.dp + statusBarPaddingValues.calculateTopPadding())
                    .padding(top = statusBarPaddingValues.calculateTopPadding())
            )
        },
        containerColor = AppColors.background,
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) { paddingValues ->
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(
                    bottom = navigationBarPaddings,
                    start = 8.dp,
                    end = 8.dp
                )
        ) {

            // 类别标签页 - 吸顶
            stickyHeader(key = "category_tabs") {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(AppColors.background)
                        .padding(top = 4.dp, bottom = 8.dp)
                ) {
                    LazyRow(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight()
                            .padding(bottom = 8.dp),
                        horizontalArrangement = Arrangement.Start,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        item {
                            CustomTabItem(
                                text = stringResource(R.string.agent_recommend),
                                isSelected = selectedTabIndex == 0,
                                onClick = {
                                    selectedTabIndex = 0
                                    viewModel.loadAllAgents()
                                }
                            )
                        }

                        item {
                            TabSpacer()
                        }

                        // 动态添加分类标签
                        viewModel.categories.forEachIndexed { index, category ->
                            item {
                                CustomTabItem(
                                    text = category.name,
                                    isSelected = selectedTabIndex == index + 1,
                                    onClick = {
                                        selectedTabIndex = index + 1
                                        viewModel.loadAgentsByCategory(category.id)
                                    }
                                )
                            }

                            item {
                                TabSpacer()
                            }
                        }
                    }
                }
            }
            // 推荐内容区域
            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp)
                ) {
                    when {
                        selectedTabIndex == 0 -> {
                            AgentViewPagerSection(agentItems = viewModel.agentItems.take(15), viewModel)
                        }
                        selectedTabIndex in 1..viewModel.categories.size -> {
                            AgentViewPagerSection(agentItems = viewModel.agentItems.take(15), viewModel)
                        }
                        else -> {
                            val shuffledAgents = viewModel.agentItems.shuffled().take(15)
                            AgentViewPagerSection(agentItems = shuffledAgents, viewModel)
                        }
                    }
                }
            }

            if (viewModel.chatRooms.isNotEmpty()) {
                // 热门聊天室
                stickyHeader(key = "hot_rooms_header") {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(AppColors.background)
                            .padding(top = 8.dp, bottom = 12.dp),
                        horizontalArrangement = Arrangement.Start,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.rider_pro_hot_room),
                            contentDescription = "chat room",
                            modifier = Modifier.size(28.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        androidx.compose.material3.Text(
                            text = stringResource(R.string.hot_rooms),
                            fontSize = 16.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W900,
                            color = AppColors.text
                        )
                    }
                }

                // 热门聊天室网格
                items(viewModel.chatRooms.chunked(2)) { rowRooms ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 12.dp),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        rowRooms.forEach { chatRoom ->
                            ChatRoomCard(
                                chatRoom = chatRoom,
                                navController = LocalNavController.current,
                                modifier = Modifier.weight(1f)
                            )
                        }
                        if (rowRooms.size == 1) {
                            Spacer(modifier = Modifier.weight(1f))
                        }
                    }
                }
            }

            // 只有当热门聊天室有数据时，才展示“发现更多”区域
            if (viewModel.chatRooms.isNotEmpty()) {
                item { Spacer(modifier = Modifier.height(20.dp)) }

                // "发现更多" 标题 - 吸顶
                stickyHeader(key = "discover_more") {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(AppColors.background)
                            .padding(top = 8.dp, bottom = 12.dp),
                        horizontalArrangement = Arrangement.Start,
                        verticalAlignment = Alignment.Bottom
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.bars_x_buttons_home_n_copy_2),
                            contentDescription = "agent",
                            modifier = Modifier.size(28.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        androidx.compose.material3.Text(
                            text = stringResource(R.string.agent_find),
                            fontSize = 16.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W900,
                            color = AppColors.text
                        )
                    }
                }

                // Agent网格 - 使用行式布局
                items(
                    items = agentItems.chunked(2),
                    key = { row -> row.firstOrNull()?.openId ?: "" }
                ) { rowItems ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 16.dp),
                        horizontalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        rowItems.forEach { agentItem ->
                            Box(
                                modifier = Modifier.weight(1f)
                            ) {
                                AgentCardSquare(
                                    agentItem = agentItem,
                                    viewModel = viewModel,
                                    navController = LocalNavController.current
                                )
                            }
                        }
                        // 如果这一行只有一个item，添加一个空的占位符
                        if (rowItems.size == 1) {
                            Spacer(modifier = Modifier.weight(1f))
                        }
                    }
                }

                // 加载更多指示器（仅在展示"发现更多"时显示）
                if (viewModel.isLoadingMore) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 24.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            LottieAnimation(
                                composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                                iterations = LottieConstants.IterateForever,
                                modifier = Modifier.size(80.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun AgentGridLayout(
    agentItems: List<AgentItem>,
    viewModel: AgentViewModel,
    navController: NavHostController
) {
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        // 将agentItems按两列分组
        agentItems.chunked(2).forEachIndexed { rowIndex, rowItems ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(
                        top = if (rowIndex == 0) 30.dp else 20.dp, // 第一行添加更多顶部间距
                        bottom = 20.dp
                    ),
                horizontalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 第一列
                Box(
                    modifier = Modifier.weight(1f)
                ) {
                    AgentCardSquare(
                        agentItem = rowItems[0],
                        viewModel = viewModel,
                        navController = navController
                    )
                }

                // 第二列（如果存在）
                if (rowItems.size > 1) {
                    Box(
                        modifier = Modifier.weight(1f)
                    ) {
                        AgentCardSquare(
                            agentItem = rowItems[1],
                            viewModel = viewModel,
                            navController = navController
                        )
                    }
                } else {
                    // 如果只有一列，添加空白占位
                    Spacer(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

@SuppressLint("SuspiciousIndentation")
@Composable
fun AgentCardSquare(
    agentItem: AgentItem,
    viewModel: AgentViewModel,
    navController: NavHostController
) {
    val AppColors = LocalAppTheme.current
    val cardHeight = 210.dp

    // 防抖状态
    var lastClickTime by remember { mutableStateOf(0L) }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(cardHeight)
            .clip(RoundedCornerShape(12.dp))
            .noRippleClickable {
                if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                        viewModel.goToProfile(agentItem.openId, navController)
                    }) {
                    lastClickTime = System.currentTimeMillis()
                }
            }
    ) {
        // 背景大图
            CustomAsyncImage(
                imageUrl = agentItem.avatar,
            contentDescription = agentItem.title,
            modifier = Modifier.fillMaxSize(),
                contentScale = androidx.compose.ui.layout.ContentScale.Crop,
            defaultRes = R.mipmap.rider_pro_agent
        )

        // 底部渐变与文字
        Box(
            modifier = Modifier
                .align(Alignment.BottomStart)
                .fillMaxWidth()
                .background(
                    Brush.verticalGradient(
                        0f to Color.Transparent,
                        1f to Color(0xB2000000)
                    )
                )
                .padding(12.dp)
        ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                    .padding(bottom = 40.dp) // 为底部聊天按钮预留空间
        ) {
            androidx.compose.material3.Text(
                text = agentItem.title,
                    color = Color.White,
                fontSize = 14.sp,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.W700,
                maxLines = 1,
                    overflow = TextOverflow.Ellipsis
            )
                Spacer(modifier = Modifier.height(4.dp))
            androidx.compose.material3.Text(
                text = agentItem.desc,
                    color = Color.White.copy(alpha = 0.92f),
                    fontSize = 11.sp,
                maxLines = 2,
                    overflow = TextOverflow.Ellipsis
            )
            }
        }

        // 底部居中 Chat 按钮
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 12.dp)
                .width(70.dp)
                .height(32.dp)
                .background(AppColors.text, RoundedCornerShape(16.dp))
                .noRippleClickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                                navController.navigate(NavigationRoute.Login.route)
                            } else {
                                viewModel.createSingleChat(agentItem.openId)
                                viewModel.goToChatAi(agentItem.openId, navController)
                            }
                        }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            androidx.compose.material3.Text(
                text = stringResource(R.string.chat),
                color = AppColors.background,
                fontSize = 13.sp,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W600
            )
        }
    }
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AgentViewPagerSection(agentItems: List<AgentItem>,viewModel: AgentViewModel) {
    val AppColors = LocalAppTheme.current
    if (agentItems.isEmpty()) return

    val pagerState = rememberPagerState(pageCount = { agentItems.size })
    val screenWidth = LocalConfiguration.current.screenWidthDp.dp
    val cardAspect = 1133.5f / 846.4f
    // 外层 LazyColumn 左右各 8dp + Pager contentPadding 左右各 20dp
    val horizontalPaddings = 56.dp
    val pagerHeight = (screenWidth - horizontalPaddings) * cardAspect

    Column {
        Box(
            modifier = Modifier
                .height(pagerHeight)
        ) {
            HorizontalPager(
                state = pagerState,
                modifier = Modifier.fillMaxSize(),
                contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 20.dp),
                pageSpacing = 12.dp
            ) { page ->
                // 缩放效果
                val pageOffset = (
                        (pagerState.currentPage - page) + pagerState
                            .currentPageOffsetFraction
                        ).coerceIn(-1f, 1f)
                val scale = 1f - (0.06f * kotlin.math.abs(pageOffset))

                AgentLargeCard(
                    agentItem = agentItems[page],
                    viewModel = viewModel,
                    navController = LocalNavController.current,
                    modifier = Modifier
                        .graphicsLayer {
                            scaleX = scale
                            scaleY = scale
                        }
                )
            }
        }
    }
}

@SuppressLint("SuspiciousIndentation")
@Composable
fun AgentLargeCard(
    agentItem: AgentItem,
    viewModel: AgentViewModel,
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val AppColors = LocalAppTheme.current
    var lastClickTime by remember { mutableStateOf(0L) }

    Box(
        modifier = modifier
            .fillMaxWidth()
            .aspectRatio(846.4f / 1133.5f)
            .clip(RoundedCornerShape(24.dp))
            .noRippleClickable {
                if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                        viewModel.goToProfile(agentItem.openId, navController)
                    }) {
                    lastClickTime = System.currentTimeMillis()
                }
            }
    ) {
        // 背景大图
        CustomAsyncImage(
            imageUrl = agentItem.avatar,
            contentDescription = agentItem.title,
            modifier = Modifier.fillMaxSize(),
            contentScale = androidx.compose.ui.layout.ContentScale.Crop,
            defaultRes = R.mipmap.rider_pro_agent
        )

        // 底部渐变与文字
        Box(
            modifier = Modifier
                .align(Alignment.BottomStart)
                .fillMaxWidth()
                .background(
                    Brush.verticalGradient(
                        0f to Color.Transparent,
                        1f to Color(0xB2000000)
                    )
                )
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 56.dp) // 为底部聊天按钮预留空间
            ) {
                androidx.compose.material3.Text(
                    text = agentItem.title,
                    color = Color.White,
                    fontSize = 20.sp,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.W700,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Spacer(modifier = Modifier.height(8.dp))
                androidx.compose.material3.Text(
                    text = agentItem.desc,
                    color = Color.White.copy(alpha = 0.92f),
                    fontSize = 14.sp,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }

        // 底部居中 Chat 按钮
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 16.dp)
                .widthIn(min = 180.dp)
                .fillMaxWidth(0.65f)
                .height(44.dp)
                .background(AppColors.text, RoundedCornerShape(22.dp))
                .noRippleClickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                                navController.navigate(NavigationRoute.Login.route)
                            } else {
                                viewModel.createSingleChat(agentItem.openId)
                                viewModel.goToChatAi(agentItem.openId, navController)
                            }
                        }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            androidx.compose.material3.Text(
                text = stringResource(R.string.chat),
                color = AppColors.background,
                fontSize = 16.sp,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W600
            )
        }
    }
}

@Composable
fun AgentPage(viewModel: AgentViewModel,agentItems: List<AgentItem>, page: Int, modifier: Modifier = Modifier,navController: NavHostController) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(horizontal = 0.dp)
    ) {
        // 显示3个agent
        agentItems.forEachIndexed { index, agentItem ->
            AgentCard2(agentItem = agentItem, viewModel = viewModel, navController = LocalNavController.current)
            if (index < agentItems.size - 1) {
                Spacer(modifier = Modifier.height(8.dp))
            }
        }
    }
}

@SuppressLint("SuspiciousIndentation")
@Composable
fun AgentCard2(viewModel: AgentViewModel,agentItem: AgentItem,navController: NavHostController) {
    val AppColors = LocalAppTheme.current

    // 防抖状态
    var lastClickTime by remember { mutableStateOf(0L) }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 3.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 左侧头像
        Box(
            modifier = Modifier
                .size(48.dp)
                .background(Color(0x00F5F5F5), RoundedCornerShape(24.dp))
                .clickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                            viewModel.goToProfile(agentItem.openId, navController)
                        }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            CustomAsyncImage(
                imageUrl = agentItem.avatar,
                contentDescription = "Agent头像",
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(24.dp)),
                contentScale = androidx.compose.ui.layout.ContentScale.Crop,
                defaultRes = R.mipmap.group_copy
            )
        }

        Spacer(modifier = Modifier.width(12.dp))

        // 中间文字内容
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(end = 8.dp)
        ) {
            // 标题
            androidx.compose.material3.Text(
                text = agentItem.title,
                fontSize = 14.sp,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W600,
                color = AppColors.text,
                maxLines = 1,
                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
            )

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

            // 描述
            androidx.compose.material3.Text(
                text = agentItem.desc,
                fontSize = 12.sp,
                color = AppColors.secondaryText,
                maxLines = 1,
                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
            )
        }

        // 右侧聊天按钮
        Box(
            modifier = Modifier
                .size(width = 60.dp, height = 32.dp)
                .background(
                    color = Color(0X147c7480),
                    shape = RoundedCornerShape(
                        topStart = 14.dp,
                        topEnd = 14.dp,
                        bottomStart = 0.dp,
                        bottomEnd = 14.dp
                    )
                )
                .clickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                            // 检查游客模式，如果是游客则跳转登录
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                                navController.navigate(NavigationRoute.Login.route)
                            } else {
                                viewModel.createSingleChat(agentItem.openId)
                                viewModel.goToChatAi(
                                    agentItem.openId,
                                    navController = navController
                                )
                            }
                        }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            androidx.compose.material3.Text(
                text = stringResource(R.string.chat),
                fontSize = 12.sp,
                color = AppColors.text,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W500
            )
        }
    }
}
@Composable
fun ChatRoomsSection(
    chatRooms: List<ChatRoom>,
    navController: NavHostController
) {
    val AppColors = LocalAppTheme.current

    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        // 标题
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(R.mipmap.rider_pro_hot_room),
                contentDescription = "chat room",
                modifier = Modifier.size(28.dp)
            )
            Spacer(modifier = Modifier.width(4.dp))
            androidx.compose.material3.Text(
                text = stringResource(R.string.hot_rooms),
                fontSize = 16.sp,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W900,
                color = AppColors.text
            )
        }

        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            chatRooms.chunked(2).forEach { rowRooms ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    rowRooms.forEach { chatRoom ->
                        ChatRoomCard(
                            chatRoom = chatRoom,
                            navController = navController,
                            modifier = Modifier.weight(1f)
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun ChatRoomCard(
    chatRoom: ChatRoom,
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val AppColors = LocalAppTheme.current
    val cardSize = 180.dp
    val viewModel: AgentViewModel = AgentViewModel
    val context = LocalContext.current

    // 防抖状态
    var lastClickTime by remember { mutableStateOf(0L) }

    // Loading 对话框
    if (viewModel.isJoiningRoom) {
        Dialog(
            onDismissRequest = { /* 阻止用户关闭对话框 */ },
            properties = DialogProperties(
                dismissOnBackPress = false,
                dismissOnClickOutside = false
            )
        ) {
            Box(
                modifier = Modifier
                    .size(120.dp)
                    .background(
                        color = Color.Transparent,
                        shape = RoundedCornerShape(12.dp)
                    ),
                contentAlignment = Alignment.Center
            ) {
                LottieAnimation(
                    composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                    iterations = LottieConstants.IterateForever,
                    modifier = Modifier.size(96.dp)
                )
            }
        }
    }

    // 正方形卡片，文字重叠在底部
    Box(
        modifier = modifier
            .size(cardSize)
            .background(AppColors.tabUnselectedBackground, RoundedCornerShape(12.dp))
            .clickable(enabled = !viewModel.isJoiningRoom) {
                if (!viewModel.isJoiningRoom && DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                        // 加入群聊房间
                        viewModel.joinRoom(
                            id = chatRoom.id,
                            name = chatRoom.name,
                            avatar = chatRoom.avatar,
                            context = context,
                            navController = navController,
                            onSuccess = {
                                // 成功加入房间
                            },
                            onError = { errorMsg ->
                                // 处理错误，可以显示Toast或其他提示
                            }
                        )
                    }) {
                    lastClickTime = System.currentTimeMillis()
                }
            }
    ) {
        // 优先显示banner，如果没有banner则显示头像
        val imageUrl = if (chatRoom.banner.isNotEmpty()) chatRoom.banner else chatRoom.avatar

        CustomAsyncImage(
            imageUrl = imageUrl,
            contentDescription = if (chatRoom.banner.isNotEmpty()) "房间banner" else "房间头像",
            modifier = Modifier
                .width(cardSize)
                .height(120.dp)
                .clip(RoundedCornerShape(
                    topStart = 12.dp,
                    topEnd = 12.dp,
                    bottomStart = 0.dp,
                    bottomEnd = 0.dp)),
            contentScale = androidx.compose.ui.layout.ContentScale.Crop,
            defaultRes = R.mipmap.rider_pro_agent
        )

        // 房间名称，重叠在底部
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .padding(bottom = 32.dp, start = 10.dp, end = 10.dp)
                .clip(RoundedCornerShape(12.dp))

        ) {
            androidx.compose.material3.Text(
                text = chatRoom.name,
                fontSize = 14.sp,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W900,
                color = AppColors.text,
                maxLines = 1,
                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                modifier = Modifier.fillMaxWidth(),
                textAlign = androidx.compose.ui.text.style.TextAlign.Left
            )
        }
        // 显示人数
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .padding(bottom = 10.dp, start = 10.dp, end = 10.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                Image(
                    painter = painterResource(R.drawable.rider_pro_nav_profile),
                    contentDescription = "chat",
                    modifier = Modifier.size(16.dp),
                    colorFilter = ColorFilter.tint(AppColors.secondaryText)
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text(
                    text = "${chatRoom.memberCount} ${stringResource(R.string.chatting_now)}",
                    fontSize = 12.sp,
                    modifier = Modifier
                        .alpha(0.6f)
                        .weight(1f),
                    color = AppColors.text,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.W500,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}