package com.aiosman.ravenow.ui.favourite

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
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.paging.compose.collectAsLazyPagingItems
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.comment.NoticeScreenHeader
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.favourite.FavouriteListViewModel.refreshPager
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost
import com.aiosman.ravenow.ui.network.NetworkErrorContent
import com.aiosman.ravenow.utils.NetworkUtils

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun FavouriteListPage() {
    val AppColors = LocalAppTheme.current
    val model = FavouriteListViewModel
    var dataFlow = model.favouriteMomentsFlow
    var moments = dataFlow.collectAsLazyPagingItems()
    val context = LocalContext.current
    val navController = LocalNavController.current
    val state = rememberPullRefreshState(FavouriteListViewModel.isLoading, onRefresh = {
        model.refreshPager(force = true)
    })
    LaunchedEffect(Unit) {
        refreshPager()
    }
    Column(
        modifier = Modifier.fillMaxSize().background(AppColors.background)
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .pullRefresh(state)
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 16.dp),
                ) {
                    NoticeScreenHeader(stringResource(R.string.favourites_upper), moreIcon = false)
                }
                val isNetworkAvailable = NetworkUtils.isNetworkAvailable(LocalContext.current)
                var moments = dataFlow.collectAsLazyPagingItems()

                if (!isNetworkAvailable) {
                    NetworkErrorContent(
                        onReload = {
                            model.refreshPager(force = true)
                        }
                    )
                } else if(moments.itemCount == 0) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(top=189.dp),
                        contentAlignment = Alignment.TopCenter
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Image(
                                painter = painterResource(
                                    id = if (com.aiosman.ravenow.AppState.darkMode) R.mipmap.empty_img
                                    else R.mipmap.empty_img),
                                contentDescription = "No favourites",
                                modifier = Modifier.size(181.dp, 153.dp)
                            )
                            Spacer(modifier = Modifier.size(9.dp)) // 调整间距为9dp
                            Text(
                                text = stringResource(R.string.favourites_null),
                                color = AppColors.text,
                                fontSize = 16.sp,
                                fontWeight = FontWeight.W600
                            )
                        }
                    }
                }else{
                    LazyVerticalGrid(
                        columns = GridCells.Fixed(3),
                        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp)
                    ) {
                        items(moments.itemCount) { idx ->
                            val momentItem = moments[idx] ?: return@items
                            // 获取缩略图URL：优先使用图片，如果没有图片则使用视频缩略图
                            val thumbnailUrl = when {
                                momentItem.images.isNotEmpty() -> momentItem.images[0].thumbnail
                                momentItem.videos != null && momentItem.videos.isNotEmpty() -> {
                                    momentItem.videos.first().thumbnailUrl ?: momentItem.videos.first().thumbnailDirectUrl
                                }
                                else -> null
                            }
                            
                            if (thumbnailUrl == null) return@items
                            
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .aspectRatio(1f)
                                    .padding(2.dp)
                                    .noRippleClickable {
                                        navController.navigateToPost(
                                            id = momentItem.id,
                                            highlightCommentId = 0,
                                            initImagePagerIndex = 0
                                        )
                                    }
                            ) {
                                CustomAsyncImage(
                                    imageUrl = thumbnailUrl,
                                    contentDescription = "",
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .clip(RoundedCornerShape(8.dp)),
                                    context = context
                                )
                                if (momentItem.images.size > 1) {
                                    Box(
                                        modifier = Modifier
                                            .padding(top = 8.dp, end = 8.dp)
                                            .align(Alignment.TopEnd)
                                    ) {
                                        Image(
                                            modifier = Modifier.size(24.dp),
                                            painter = painterResource(R.drawable.rider_pro_picture_more),
                                            contentDescription = "",
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
            PullRefreshIndicator(
                FavouriteListViewModel.isLoading,
                state,
                Modifier.align(Alignment.TopCenter)
            )

        }

    }
}