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

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
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.AgentCard
import com.aiosman.ravenow.ui.composables.rememberDebouncer

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HotAgent() {
    val AppColors = LocalAppTheme.current
    val model = HotAgentViewModel
    var agentList = model.agentList
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    val state = rememberPullRefreshState(model.refreshing, onRefresh = {
        model.refreshPager(pullRefresh = true)
    })
    val listState = rememberLazyListState()

    // observe list scrolling
    val reachedBottom by remember {
        derivedStateOf {
            val lastVisibleItem = listState.layoutInfo.visibleItemsInfo.lastOrNull()
            lastVisibleItem?.index != 0 && lastVisibleItem?.index == listState.layoutInfo.totalItemsCount - 2
        }
    }

    // load more if scrolled to bottom
    LaunchedEffect(reachedBottom) {
        if (reachedBottom && !model.isLoading && model.hasNext) {
            model.loadMore()
        }
    }
    
    // 只在初始化页面时刷新
    LaunchedEffect(Unit) {
        // 只有在列表完全为空且没有正在加载时才进行初始化刷新
        if (model.agentList.isEmpty() && !model.isLoading) {
            model.refreshPager()
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        if(agentList.isEmpty() && !model.isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.rider_pro_following_empty),
                        contentDescription = null,
                        modifier = Modifier.size(140.dp)
                    )
                    Spacer(modifier = Modifier.size(32.dp))
                    Text(
                        text = "您还没有创建任何智能体",
                        color = AppColors.text,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W600
                    )
                    Spacer(modifier = Modifier.size(16.dp))
                    Text(
                        text = "点击开始创建您的第一个智能体",
                        color = AppColors.text,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W400
                    )
                }
            }
        } else {
            Box(Modifier.pullRefresh(state)) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    state = listState
                ) {
                    items(
                        agentList.size,
                        key = { idx -> idx }
                    ) { idx ->
                        val agentItem = agentList[idx]
                        val chatDebouncer = rememberDebouncer()
                        val avatarDebouncer = rememberDebouncer()
                        AgentCard(
                            agentEntity = agentItem,
                            onClick =  {
                                chatDebouncer {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        model.createSingleChat(agentItem.openId)
                                        model.goToChatAi(agentItem.openId, navController)
                                    }
                                }
                            },
                            onAvatarClick = {
                                avatarDebouncer {
                                model.goToProfile(agentItem.openId, navController)
                            }
                            }
                        )
                    }
                    
                    // 加载更多指示器
                    if (model.isLoading && agentList.isNotEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth(),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = AppColors.main
                                )
                            }
                        }
                    }
                }
                PullRefreshIndicator(model.refreshing, state, Modifier.align(Alignment.TopCenter))
            }
        }
        
        // 错误信息显示
        model.error?.let { error ->
            Box(
                modifier = Modifier
                    .fillMaxWidth(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = error,
                    color = AppColors.error,
                    fontSize = 14.sp
                )
            }
        }
    }
}