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

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
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.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
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.index.tabs.shorts.ShortViewCompose
import kotlinx.coroutines.launch

/**
 * 短视频页面
 */
@Composable
fun ShortVideoScreen(
    isPageVisible: Boolean = true
) {
    val viewModel = ShortVideoViewModel
    val allMoments = viewModel.moments
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    val AppColors = LocalAppTheme.current
    val momentLoader = viewModel.momentLoader
    // 记录当前播放的短视频索引，切换 Tab 返回时恢复
    val currentIndex = rememberSaveable { androidx.compose.runtime.mutableStateOf(0) }
    
    // 过滤出包含视频的动态
    val videoMoments = remember(allMoments) {
        val filtered = allMoments.filter { it.videos != null && it.videos.isNotEmpty() }
        Log.d("ShortVideoScreen", "过滤视频动态 - 总动态数: ${allMoments.size}, 包含视频的动态数: ${filtered.size}")
        filtered.forEach { moment ->
            Log.d("ShortVideoScreen", "视频动态 ID: ${moment.id}, 视频数: ${moment.videos?.size}, 第一个视频URL: ${moment.videos?.firstOrNull()?.url}")
        }
        filtered
    }
    
    // 初始加载数据
    LaunchedEffect(Unit) {
        Log.d("ShortVideoScreen", "开始加载数据")
        viewModel.refreshPager()
    }
    
    // 加载更多数据
    LaunchedEffect(allMoments.size, videoMoments.size) {
        Log.d("ShortVideoScreen", "检查是否需要加载更多 - allMoments: ${allMoments.size}, videoMoments: ${videoMoments.size}, hasNext: ${momentLoader.hasNext}, isLoading: ${momentLoader.isLoading}")
        if (allMoments.isNotEmpty() && videoMoments.size < 10 && momentLoader.hasNext && !momentLoader.isLoading) {
            // 如果视频数量少于10个，尝试加载更多
            Log.d("ShortVideoScreen", "开始加载更多数据")
            viewModel.loadMore()
        }
    }
    
    // 加载状态
    if (momentLoader.isLoading && videoMoments.isEmpty()) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background),
            contentAlignment = Alignment.Center
        ) {
            LottieAnimation(
                composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                iterations = LottieConstants.IterateForever,
                modifier = Modifier.size(96.dp)
            )
        }
    }
    // 错误状态
    else if (momentLoader.error != null && videoMoments.isEmpty()) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "加载失败: ${momentLoader.error}",
                color = AppColors.error,
                fontSize = 14.sp
            )
        }
    }
    // 空状态 - 已加载但无视频
    else if (!momentLoader.isLoading && videoMoments.isEmpty() && allMoments.isNotEmpty()) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "暂无短视频\n已加载 ${allMoments.size} 条动态，但都不包含视频",
                color = AppColors.text,
                fontSize = 16.sp
            )
        }
    }
    // 初始状态 - 还没有加载过数据
    else if (!momentLoader.isLoading && videoMoments.isEmpty() && allMoments.isEmpty() && momentLoader.error == null) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background),
            contentAlignment = Alignment.Center
        ) {
            LottieAnimation(
                composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                iterations = LottieConstants.IterateForever,
                modifier = Modifier.size(80.dp)
            )
        }
    }
    // 显示视频列表
    else if (videoMoments.isNotEmpty()) {
        ShortViewCompose(
            videoMoments = videoMoments,
            clickItemPosition = currentIndex.value,
            onLikeClick = { moment ->
                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                    navController.navigate(NavigationRoute.Login.route)
                } else {
                    scope.launch {
                        if (moment.liked) {
                            viewModel.dislikeMoment(moment.id)
                        } else {
                            viewModel.likeMoment(moment.id)
                        }
                    }
                }
            },
            onCommentClick = { moment ->
                // 点击评论图标只是打开评论弹窗，不应该增加评论数
            },
            onCommentAdded = { moment ->
                // 评论添加后的回调，更新评论数
                scope.launch {
                    viewModel.onAddComment(moment.id)
                }
            },
            onFavoriteClick = { moment ->
                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                    navController.navigate(NavigationRoute.Login.route)
                } else {
                    scope.launch {
                        if (moment.isFavorite) {
                            viewModel.unfavoriteMoment(moment.id)
                        } else {
                            viewModel.favoriteMoment(moment.id)
                        }
                    }
                }
            },
            onShareClick = { moment ->
                // TODO: 实现分享功能
            },
            onAvatarClick = { moment ->
                // 点击头像进入用户界面
                navController.navigate(
                    com.aiosman.ravenow.ui.NavigationRoute.AccountProfile.route.replace(
                        "{id}",
                        moment.authorId.toString()
                    )
                )
            },
            onPageChanged = { idx -> currentIndex.value = idx },
            isPageVisible = isPageVisible
        )
    }
}

