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

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.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
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.runtime.snapshotFlow
import kotlinx.coroutines.flow.collectLatest
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.unit.dp
import androidx.compose.runtime.collectAsState
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.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.search.SearchViewModel
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost

/**
 * 动态列表
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HotMomentsList() {
    val model = HotMomentViewModel
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 48.dp
    val isRefreshing by model.isRefreshing.collectAsState()
    
    LaunchedEffect(Unit) {
        model.loadMoments()
    }
    
    val state = rememberPullRefreshState(isRefreshing, onRefresh = {
        model.refreshMoments()
    })

    Column(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(state)

    ) {
        Column(
            modifier = Modifier.fillMaxWidth().background(
                AppColors.background).padding(bottom = 0.dp)
        ) {
        }

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .padding(2.dp)
        ) {
            DiscoverView()
            PullRefreshIndicator(isRefreshing, state, Modifier.align(Alignment.TopCenter))
        }
    }
}


@Composable
fun DiscoverView() {
    val model = HotMomentViewModel
    val moments by model.discoverMoments.collectAsState()
    val isLoading by model.isLoading.collectAsState()
    val context = LocalContext.current
    val navController = LocalNavController.current
    val gridState = rememberLazyGridState()
    
    // 监听滚动到底部，自动加载更多
    LaunchedEffect(gridState, moments.size) {
        snapshotFlow {
            val layoutInfo = gridState.layoutInfo
            val visibleItemsInfo = layoutInfo.visibleItemsInfo
            if (visibleItemsInfo.isNotEmpty() && moments.isNotEmpty()) {
                val lastVisibleItemIndex = visibleItemsInfo.lastOrNull()?.index ?: 0
                lastVisibleItemIndex >= moments.size - 6 // 距离底部还有6个项目时开始加载
            } else {
                false
            }
        }.collectLatest { shouldLoadMore ->
            if (shouldLoadMore && !isLoading) {
                model.loadMoments()
            }
        }
    }
    
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        state = gridState,
        modifier = Modifier.fillMaxSize().padding(bottom = 8.dp),
//        contentPadding = PaddingValues(8.dp)
    ) {
        items(moments) { momentItem ->
            val debouncer = rememberDebouncer()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .padding(2.dp)
                    .noRippleClickable {
                        debouncer {
                            navController.navigateToPost(
                                id = momentItem.id,
                                highlightCommentId = 0,
                                initImagePagerIndex = 0
                            )
                        }
                    }
            ) {
                CustomAsyncImage(
                    imageUrl = momentItem.images[0].thumbnail,
                    contentDescription = "",
                    modifier = Modifier
                        .fillMaxSize(),
                    context = context,
                    showShimmer = true
                )
                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 = "",
                        )
                    }
                }


            }

        }
    }
}