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

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Text
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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.entity.MomentEntity
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.moment.tabs.recommend.RecommendViewModel
import kotlinx.coroutines.launch

/**
 * 推荐界面主组件
 * 使用 VerticalPager 实现上下滑动切换页面
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun RecommendScreen() {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    
    val recommendationsList = RecommendViewModel.recommendations
    val loading = RecommendViewModel.isLoading
    val errorMessage = RecommendViewModel.error
    val hasMore = RecommendViewModel.hasNext
    
    // 垂直翻页状态
    val pagerState = rememberPagerState(pageCount = { recommendationsList.size })
    
    // 防抖器
    val likeDebouncer = rememberDebouncer()
    val favoriteDebouncer = rememberDebouncer()
    
    // 初始化加载数据
    LaunchedEffect(Unit) {
        RecommendViewModel.refreshRecommendations()
    }
    
    // 当翻页接近末尾时加载更多
    LaunchedEffect(pagerState.currentPage, recommendationsList.size) {
        if (recommendationsList.isNotEmpty() && pagerState.currentPage >= recommendationsList.size - 2 && hasMore) {
            RecommendViewModel.loadMore()
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        when {
            // 加载中
            loading && recommendationsList.isEmpty() -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    LottieAnimation(
                        composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                        iterations = LottieConstants.IterateForever,
                        modifier = Modifier.size(96.dp)
                    )
                }
            }
            
            // 错误状态
            errorMessage != null && recommendationsList.isEmpty() -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "加载失败: $errorMessage",
                        color = AppColors.error,
                        fontSize = 14.sp
                    )
                }
            }
            
            // 空状态
            recommendationsList.isEmpty() -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无推荐内容",
                        color = AppColors.text,
                        fontSize = 16.sp
                    )
                }
            }
            
            // 显示推荐列表
            else -> {
                VerticalPager(
                    state = pagerState,
                    modifier = Modifier.fillMaxSize()
                ) { page ->
                    val item = recommendationsList.getOrNull(page) ?: return@VerticalPager
                    
                    Box(modifier = Modifier.fillMaxSize()) {
                        when (item) {
                            is RecommendationDisplayItem.Post -> {
                                val moment = item.moment
                                when {
                                    // 新闻类型
                                    moment.isNews -> {
                                        NewsRecommendationItem(
                                            moment = moment,
                                            onCommentClick = {
                                                // TODO: 打开评论弹窗
                                            },
                                            onReadFullClick = {
                                                // TODO: 打开全文弹窗
                                            },
                                            onLikeClick = {
                                                likeDebouncer {
                                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                                        navController.navigate(NavigationRoute.Login.route)
                                                    } else {
                                                        scope.launch {
                                                            if (moment.liked) {
                                                                RecommendViewModel.dislikeMoment(moment.id)
                                                            } else {
                                                                RecommendViewModel.likeMoment(moment.id)
                                                            }
                                                        }
                                                    }
                                                }
                                            },
                                            onFavoriteClick = {
                                                favoriteDebouncer {
                                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                                        navController.navigate(NavigationRoute.Login.route)
                                                    } else {
                                                        scope.launch {
                                                            if (moment.isFavorite) {
                                                                RecommendViewModel.unfavoriteMoment(moment.id)
                                                            } else {
                                                                RecommendViewModel.favoriteMoment(moment.id)
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        )
                                    }
                                    
                                    // 短视频类型
                                    !moment.videos.isNullOrEmpty() -> {
                                        VideoRecommendationItem(
                                            moment = moment,
                                            isVisible = pagerState.currentPage == page,
                                            modifier = Modifier.fillMaxSize(),
                                            onLikeClick = { m ->
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                } else {
                                                    scope.launch {
                                                        if (m.liked) {
                                                            RecommendViewModel.dislikeMoment(m.id)
                                                        } else {
                                                            RecommendViewModel.likeMoment(m.id)
                                                        }
                                                    }
                                                }
                                            },
                                            onCommentClick = { m ->
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                } else {
                                                    scope.launch {
                                                        RecommendViewModel.onAddComment(m.id)
                                                    }
                                                }
                                            },
                                            onFavoriteClick = { m ->
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                } else {
                                                    scope.launch {
                                                        if (m.isFavorite) {
                                                            RecommendViewModel.unfavoriteMoment(m.id)
                                                        } else {
                                                            RecommendViewModel.favoriteMoment(m.id)
                                                        }
                                                    }
                                                }
                                            },
                                            onShareClick = { _ ->
                                                // TODO: 实现分享功能
                                            }
                                        )
                                    }
                                    
                                    // 普通动态类型
                                    else -> {
                                        PostRecommendationItem(
                                            moment = moment,
                                            modifier = Modifier.fillMaxSize(),
                                            onLikeClick = { m ->
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                } else {
                                                    scope.launch {
                                                        if (m.liked) {
                                                            RecommendViewModel.dislikeMoment(m.id)
                                                        } else {
                                                            RecommendViewModel.likeMoment(m.id)
                                                        }
                                                    }
                                                }
                                            },
                                            onCommentClick = { m ->
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                } else {
                                                    scope.launch {
                                                        RecommendViewModel.onAddComment(m.id)
                                                    }
                                                }
                                            },
                                            onFavoriteClick = { m ->
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                } else {
                                                    scope.launch {
                                                        if (m.isFavorite) {
                                                            RecommendViewModel.unfavoriteMoment(m.id)
                                                        } else {
                                                            RecommendViewModel.favoriteMoment(m.id)
                                                        }
                                                    }
                                                }
                                            },
                                            onShareClick = { _ ->
                                                // TODO: 实现分享功能
                                            }
                                        )
                                    }
                                }
                            }
                            
                            is RecommendationDisplayItem.Prompt -> {
                                PromptRecommendationItem(
                                    id = item.id,
                                    title = item.title,
                                    desc = item.desc,
                                    avatar = item.avatar,
                                    openId = item.openId,
                                    modifier = Modifier.fillMaxSize()
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

