package com.aiosman.ravenow.ui.index.tabs.moment.tabs.dynamic

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
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.runtime.Composable
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 com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.MomentCard
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import kotlinx.coroutines.launch

/**
 * 动态列表
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Dynamic() {
    val model = DynamicViewModel
    val moments = model.moments
    val navController = LocalNavController.current

    val scope = rememberCoroutineScope()
    val state = rememberPullRefreshState(model.refreshing, onRefresh = {
        model.refreshPager(
            pullRefresh = true
        )
    })
    val listState = rememberLazyListState()

    // 用于跟踪是否已经触发过加载更多
    var hasTriggeredLoadMore by remember { mutableStateOf(false) }

    // observe list scrolling with simplified logic
    val reachedBottom by remember {
        derivedStateOf {
            val layoutInfo = listState.layoutInfo
            val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
            val totalItems = layoutInfo.totalItemsCount

            if (lastVisibleItem == null || totalItems == 0) {
                false
            } else {
                val isLastItemVisible = lastVisibleItem.index >= totalItems - 2

                // 简化逻辑：只要滑动到底部且还没有触发过，就触发加载
                isLastItemVisible && !hasTriggeredLoadMore
            }
        }
    }

    // load more if scrolled to bottom
    LaunchedEffect(reachedBottom) {
        if (reachedBottom) {
            hasTriggeredLoadMore = true
            model.loadMore()
        }
    }
    LaunchedEffect(Unit) {
        model.refreshPager()
    }

    // 监听数据变化，重置加载状态
    LaunchedEffect(moments.size) {
        if (moments.size > 0) {
            // 延迟重置，确保数据已经稳定
            kotlinx.coroutines.delay(500)
            hasTriggeredLoadMore = false
        }
    }
    Column(
        modifier = Modifier
            .fillMaxSize()

    ) {
        Box(Modifier.pullRefresh(state)) {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                state = listState
            ) {
                items(
                    moments.size,
                    key = { idx -> idx }
                ) { idx ->
                    //处理下标越界
                    if (idx < 0 || idx >= moments.size) return@items
                    val momentItem = moments[idx] ?: return@items

                    val commentDebouncer = rememberDebouncer()
                    val likeDebouncer = rememberDebouncer()
                    val favoriteDebouncer = rememberDebouncer()
                    val followDebouncer = rememberDebouncer()

                    MomentCard(
                        momentEntity = momentItem,
                        onAddComment = {
                            commentDebouncer {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                    navController.navigate(NavigationRoute.Login.route)
                                } else {
                                    scope.launch {
                                        model.onAddComment(momentItem.id)
                                    }
                                }
                            }
                        },
                        onLikeClick = {
                            likeDebouncer {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                    navController.navigate(NavigationRoute.Login.route)
                                } else {
                                    scope.launch {
                                        if (momentItem.liked) {
                                            model.dislikeMoment(momentItem.id)
                                        } else {
                                            model.likeMoment(momentItem.id)
                                        }
                                    }
                                }
                            }
                        },
                        onFavoriteClick = {
                            favoriteDebouncer {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                    navController.navigate(NavigationRoute.Login.route)
                                } else {
                                    scope.launch {
                                        if (momentItem.isFavorite) {
                                            model.unfavoriteMoment(momentItem.id)
                                        } else {
                                            model.favoriteMoment(momentItem.id)
                                        }
                                    }
                                }
                            }
                        },
                        onFollowClick = {
                            followDebouncer {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.FOLLOW_USER)) {
                                    navController.navigate(NavigationRoute.Login.route)
                                } else {
                                    model.followAction(momentItem)
                                }
                            }
                        },
                        showFollowButton = true
                    )
                }
            }
        }
    }
}
