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

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.PaddingValues
import androidx.compose.foundation.layout.Spacer
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.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
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.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
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.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.composables.MomentCard
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import kotlinx.coroutines.launch

/**
 * 动态列表
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TimelineMomentsList() {
    val model = TimelineMomentViewModel
    var moments = model.moments
    val AppColors = LocalAppTheme.current
    val scope = rememberCoroutineScope()
    val state = rememberPullRefreshState(model.refreshing, onRefresh = {
        model.refreshPager(
            pullRefresh = true
        )
    })
    LaunchedEffect(Unit) {
        model.refreshPager()
    }
    val listState = rememberLazyListState()

    // observe list scrolling
    val reachedBottom by remember {
        derivedStateOf {
            val lastVisibleItem = listState.layoutInfo.visibleItemsInfo.lastOrNull()
            lastVisibleItem?.index != 0 && lastVisibleItem?.index == listState.layoutInfo.totalItemsCount - 2
        }
    }
    LaunchedEffect(reachedBottom) {
        if (reachedBottom) {
            model.loadMore()
        }
    }
    if (moments.isEmpty()) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 188.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                val exploreDebouncer = rememberDebouncer()
                Image(
                    painter = painterResource(
                        id = if(AppState.darkMode) R.mipmap.qst_gz_qs_as_img
                        else R.mipmap.qst_gz_qs_img),
                    contentDescription = null,
                    modifier = Modifier.size(140.dp)
                )
                Spacer(modifier = Modifier.size(24.dp))
                Text(
                    text = "连接世界，从关注开始",
                    color = AppColors.text,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.size(8.dp))
                Text(
                    text = "不如从一个 Agent 开始认识这世界？",
                    color = AppColors.text,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.W400
                )
                Spacer(modifier = Modifier.size(16.dp))
                ExploreButton(
                    onClick = {
                        exploreDebouncer {
                            /* TODO: 添加点击事件处理 */
                        } }
                )
            }
        }
    } else {
        Column(
            modifier = Modifier
                .fillMaxSize()
        ) {
            Box(Modifier.pullRefresh(state)) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    state = listState
                ) {
                    items(
                        moments.size,
                        key = { idx -> moments.getOrNull(idx)?.id ?: idx }
                    ) { idx ->
                        moments.getOrNull(idx)?.let { momentItem ->
                            val commentDebouncer = rememberDebouncer()
                            val likeDebouncer = rememberDebouncer()
                            val favoriteDebouncer = rememberDebouncer()
                            val followDebouncer = rememberDebouncer()

                            MomentCard(
                                momentEntity = momentItem,
                                onAddComment = {
                                    commentDebouncer {
                                        scope.launch {
                                            model.onAddComment(momentItem.id)
                                        }
                                    }
                                },
                                onLikeClick = {
                                    likeDebouncer {
                                        scope.launch {
                                            if (momentItem.liked) {
                                                model.dislikeMoment(momentItem.id)
                                            } else {
                                                model.likeMoment(momentItem.id)
                                            }
                                        }
                                    }
                                },
                                onFavoriteClick = {
                                    favoriteDebouncer {
                                        scope.launch {
                                            if (momentItem.isFavorite) {
                                                model.unfavoriteMoment(momentItem.id)
                                            } else {
                                                model.favoriteMoment(momentItem.id)
                                            }
                                        }
                                    }
                                },
                                onFollowClick = {
                                    followDebouncer {
                                        model.followAction(momentItem)
                                    }
                                },
                                showFollowButton = false
                            )
                        }
                    }

                }
                PullRefreshIndicator(model.refreshing, state, Modifier.align(Alignment.TopCenter))
            }
        }
    }
}
@Composable
fun ExploreButton(
    onClick: () -> Unit
) {
    val gradientBrush = Brush.linearGradient(
        colors = listOf(
            Color(0xFFee2a33),
            Color(0xFFd80264),
            Color(0xFF664c92)
        )
    )

    Button(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 144.dp)
            .height(48.dp),
        shape = RoundedCornerShape(30.dp),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Transparent
        ),
        contentPadding = PaddingValues(0.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(gradientBrush),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "去探索",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
        }
    }
}