package com.aiosman.ravenow.ui.comment.notice

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
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.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.CommentEntity
import com.aiosman.ravenow.exp.timeAgo
import com.aiosman.ravenow.ui.NavigationRoute
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.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost
import kotlinx.coroutines.launch

@Composable
fun CommentNoticeScreen() {
    val viewModel = viewModel<CommentNoticeListViewModel>(
        key = "CommentNotice",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return CommentNoticeListViewModel() as T
            }
        }
    )
    val context = LocalContext.current
    LaunchedEffect(Unit) {
        viewModel.initData(context)
    }
    var dataFlow = viewModel.commentItemsFlow
    var comments = dataFlow.collectAsLazyPagingItems()
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current

    Column(
        modifier = Modifier.fillMaxSize().background(color = AppColors.background)
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            NoticeScreenHeader(stringResource(R.string.comment), moreIcon = false)
        }
        if (comments.itemCount == 0 && comments.loadState.refresh is LoadState.NotLoading) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(top = 149.dp),
                contentAlignment = Alignment.TopCenter
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    androidx.compose.foundation.Image(
                        painter = painterResource(
                            id =if(AppState.darkMode) R.mipmap.qst_pl_qs_as_img
                            else R.mipmap.qst_pl_qs_img),
                        contentDescription = "No Comment",
                        modifier = Modifier.size(181.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 = "去发布动态，让更多人参与对话",
                        color = AppColors.text,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.W400
                    )
                }
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize().padding(horizontal = 16.dp)
            ) {
                items(comments.itemCount) { index ->
                    comments[index]?.let { comment ->
                        CommentNoticeItem(comment) {
                            viewModel.updateReadStatus(comment.id)
                            viewModel.viewModelScope.launch {
                                var highlightCommentId = comment.id
                                comment.parentCommentId?.let {
                                    highlightCommentId = it
                                }
                                navController.navigateToPost(
                                    id = comment.post!!.id,
                                    highlightCommentId = highlightCommentId,
                                    initImagePagerIndex = 0
                                )
                            }
                        }
                    }
                }
                // handle load error
                when {
                    comments.loadState.append is LoadState.Loading -> {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(64.dp)
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                LinearProgressIndicator(
                                    modifier = Modifier.width(160.dp),
                                    color = AppColors.main
                                )
                            }
                        }
                    }

                    comments.loadState.append is LoadState.Error -> {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(64.dp)
                                    .noRippleClickable {
                                        comments.retry()
                                    },
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "Load comment error, click to retry",
                                    color = AppColors.text
                                )
                            }
                        }
                    }
                }
                item {
                    Spacer(modifier = Modifier.height(72.dp))
                }
            }
        }
    }
}

@Composable
fun CommentNoticeItem(
    commentItem: CommentEntity,
    onPostClick: () -> Unit = {},
) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val AppColors = LocalAppTheme.current

    Row(
        modifier = Modifier.padding(vertical = 20.dp, horizontal = 16.dp)
    ) {
        Box {
            CustomAsyncImage(
                context = context,
                imageUrl = commentItem.avatar,
                contentDescription = commentItem.name,
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .noRippleClickable {
                        navController.navigate(
                            NavigationRoute.AccountProfile.route.replace(
                                "{id}",
                                commentItem.author.toString()
                            )
                        )
                    }
            )
        }
        Row(
            modifier = Modifier
                .weight(1f)
                .padding(start = 12.dp)
                .noRippleClickable {
                    onPostClick()
                }
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = commentItem.name,
                    fontSize = 18.sp,
                    modifier = Modifier,
                    color = AppColors.text
                )
                Spacer(modifier = Modifier.height(4.dp))
                Row {
                    var text = commentItem.comment
                    if (commentItem.parentCommentId != null) {
                        text = "Reply you: $text"
                    }
                    Text(
                        text = text,
                        fontSize = 14.sp,
                        maxLines = 1,
                        color = AppColors.secondaryText,
                        modifier = Modifier.weight(1f),
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = commentItem.date.timeAgo(context),
                        fontSize = 14.sp,
                        color = AppColors.secondaryText,
                    )
                }

            }
            Spacer(modifier = Modifier.width(24.dp))
            commentItem.post?.let {
                Box {
                    Box(
                        modifier = Modifier.padding(4.dp)
                    ) {
                        CustomAsyncImage(
                            context = context,
                            imageUrl = it.images[0].thumbnail,
                            contentDescription = "Post Image",
                            modifier = Modifier
                                .size(48.dp).clip(RoundedCornerShape(8.dp))
                        )
                        // unread indicator

                    }

                    if (commentItem.unread) {
                        Box(
                            modifier = Modifier
                                .background(AppColors.main, CircleShape)
                                .size(12.dp)
                                .align(Alignment.TopEnd)
                        )
                    }
                }


            }
        }


    }
}
