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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
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.foundation.lazy.grid.items as gridItems

// 检测是否接近列表底部的扩展函数
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 = viewModel()

    // 确保推荐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 = {
                    androidx.compose.material3.Text(
                        text = "Rave AI",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.W900,
                        color = AppColors.text
                    )
                },
                actions = {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_nav_search),
                        contentDescription = "search",
                        modifier = Modifier
                            .size(24.dp)
                            .noRippleClickable {
                                navController.navigate(NavigationRoute.Search.route)
                            },
                        colorFilter = ColorFilter.tint(AppColors.text)
                    )
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = AppColors.background
                )
            )
        },
        containerColor = AppColors.background,
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) { paddingValues ->
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(
                    bottom = navigationBarPaddings,
                    start = 16.dp,
                    end = 16.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.take(4).forEachIndexed { index, category ->
                            item {
                                CustomTabItem(
                                    text = category.name,
                                    isSelected = selectedTabIndex == index + 1,
                                    onClick = {
                                        selectedTabIndex = index + 1
                                        viewModel.loadAgentsByCategory(category.id)
                                    }
                                )
                            }

                            item {
                                TabSpacer()
                            }
                        }

                        item {
                            CustomTabItem(
                                text = "scenes",
                                isSelected = selectedTabIndex == 1,
                                onClick = {
                                    selectedTabIndex = 1
                                }
                            )
                        }

                        item {
                            TabSpacer()
                        }

                        item {
                            CustomTabItem(
                                text = "voices",
                                isSelected = selectedTabIndex == 6,
                                onClick = {
                                    selectedTabIndex = 6
                                }
                            )
                        }

                        item {
                            TabSpacer()
                        }

                        item {
                            CustomTabItem(
                                text = "anime",
                                isSelected = selectedTabIndex == 7,
                                onClick = {
                                    selectedTabIndex = 7
                                }
                            )
                        }

                        item {
                            TabSpacer()
                        }

                        item {
                            CustomTabItem(
                                text = "assist",
                                isSelected = selectedTabIndex == 8,
                                onClick = {
                                    selectedTabIndex = 8
                                }
                            )
                        }
                    }
                }
            }
            // 推荐内容区域
            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)
                        }
                    }
                }
            }


            // "发现更多" 标题 - 吸顶
            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.rider_pro_agent2),
                        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.W600,
                        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 {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 24.dp),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        androidx.compose.material3.CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = AppColors.text,
                            strokeWidth = 2.dp
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        androidx.compose.material3.Text(
                            text = "加载中...",
                            color = AppColors.secondaryText,
                            fontSize = 14.sp
                        )
                    }
                }
            }
        }
    }
}
@SuppressLint("SuspiciousIndentation")
@Composable
fun AgentCardSquare(agentItem: AgentItem, viewModel: AgentViewModel, navController: NavHostController) {
    val AppColors = LocalAppTheme.current
    val cardHeight = 200.dp
    val avatarSize = cardHeight / 3  // 头像大小为方块高度的三分之一

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

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = avatarSize / 2)
            .height(cardHeight)
            .background(AppColors.nonActive, RoundedCornerShape(12.dp))  // 修改背景颜色
            .clickable {
                if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                        viewModel.goToProfile(agentItem.openId, navController)
                    }) {
                    lastClickTime = System.currentTimeMillis()
                }
            },
        contentAlignment = Alignment.TopCenter
    ) {
        // 头像，位于方块上方居中，部分悬于方块外部
        Box(
            modifier = Modifier
                .offset(y = -avatarSize / 2)
                .size(avatarSize)
                .background(Color.White, RoundedCornerShape(avatarSize / 2))
                .clip(RoundedCornerShape(avatarSize / 2)),
            contentAlignment = Alignment.Center
        ) {
            if (agentItem.avatar.isNotEmpty()) {
                CustomAsyncImage(
                    imageUrl = agentItem.avatar,
                    contentDescription = "Agent头像",
                    modifier = Modifier
                        .size(avatarSize)
                        .clip(RoundedCornerShape(avatarSize / 2)),
                    contentScale = androidx.compose.ui.layout.ContentScale.Crop
                )
            } else {
                Image(
                    painter = painterResource(R.mipmap.rider_pro_agent),
                    contentDescription = "默认头像",
                    modifier = Modifier.size(avatarSize / 2),
                    colorFilter = ColorFilter.tint(AppColors.secondaryText)
                )
            }
        }

        // 内容区域（名称和描述）
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = avatarSize / 2 + 8.dp, start = 8.dp, end = 8.dp, bottom = 8.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            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))

            Box(
                modifier = Modifier
                    .height(85.dp)
                    .fillMaxWidth()
            ) {
                androidx.compose.material3.Text(
                    text = agentItem.desc,
                    fontSize = 12.sp,
                    color = AppColors.secondaryText,
                    maxLines = 5,
                    overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                )
            }

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

            // 聊天按钮，位于底部居中
            Box(
                modifier = Modifier
                    .width(60.dp)
                    .height(32.dp)
                    .background(
                        color = Color(0X147c7480),
                        shape = RoundedCornerShape(8.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
                )
            }
        }
    }
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AgentViewPagerSection(agentItems: List<AgentItem>,viewModel: AgentViewModel) {
    val AppColors = LocalAppTheme.current

    // 每页显示5个agent
    val itemsPerPage = 5
    val totalPages = (agentItems.size + itemsPerPage - 1) / itemsPerPage

    if (totalPages > 0) {
        val pagerState = rememberPagerState(pageCount = { totalPages })

        Column {
            // Agent内容
            Box(
                modifier = Modifier
                    .height(300.dp)
            ) {
                HorizontalPager(
                    state = pagerState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 4.dp),
                    pageSpacing = 0.dp
                ) { page ->
                    // 计算当前页面的偏移量
                    val pageOffset = (
                            (pagerState.currentPage - page) + pagerState
                                .currentPageOffsetFraction
                            ).coerceIn(-1f, 1f)

                    // 根据偏移量计算缩放比例
                    val scale = 1f - (0.1f * kotlin.math.abs(pageOffset))

                    AgentPage(
                        viewModel = viewModel,
                        agentItems = agentItems.drop(page * itemsPerPage).take(itemsPerPage),
                        page = page,
                        modifier = Modifier
                            .height(300.dp)
                            .graphicsLayer {
                                scaleX = scale
                                scaleY = scale
                            },
                        navController = LocalNavController.current,
                    )
                }
            }

            // 指示器
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(30.dp)
                    .padding(top = 12.dp),
                horizontalArrangement = androidx.compose.foundation.layout.Arrangement.Center
            ) {
                repeat(totalPages) { index ->
                    Box(
                        modifier = Modifier
                            .padding(horizontal = 4.dp)
                            .size(3.dp)
                            .background(
                                color = if (pagerState.currentPage == index) AppColors.text else AppColors.secondaryText.copy(
                                    alpha = 0.3f
                                ),
                                shape = androidx.compose.foundation.shape.CircleShape
                            )
                    )
                }
            }
        }
    }
}

@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(0xFFF5F5F5), RoundedCornerShape(24.dp))
                .clickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                            viewModel.goToProfile(agentItem.openId, navController)
                        }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            if (agentItem.avatar.isNotEmpty()) {
                CustomAsyncImage(
                    imageUrl = agentItem.avatar,
                    contentDescription = "Agent头像",
                    modifier = Modifier
                        .size(48.dp)
                        .clip(RoundedCornerShape(24.dp)),
                    contentScale = androidx.compose.ui.layout.ContentScale.Crop
                )
            } else {
                Image(
                    painter = painterResource(R.mipmap.rider_pro_agent),
                    contentDescription = "默认头像",
                    modifier = Modifier.size(24.dp),
                    colorFilter = ColorFilter.tint(AppColors.secondaryText)
                )
            }
        }

        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(8.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
            )
        }
    }
}
