package com.aiosman.ravenow.ui.like

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.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.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
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.tooling.preview.Preview
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.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.AccountLikeEntity
import com.aiosman.ravenow.exp.timeAgo
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.BottomNavigationPlaceholder
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarMaskLayout
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost
import java.util.Date
import com.aiosman.ravenow.utils.NetworkUtils
import com.aiosman.ravenow.ui.network.NetworkErrorContent
@Preview
@Composable
fun LikeNoticeScreen(includeStatusBarPadding: Boolean = true) {
    val model = LikeNoticeViewModel
    val listState = rememberLazyListState()
    var dataFlow = model.likeItemsFlow
    var likes = dataFlow.collectAsLazyPagingItems()
    val AppColors = LocalAppTheme.current

    LaunchedEffect(Unit) {
        model.reload()
        model.updateNotice()
    }

    StatusBarMaskLayout(
        darkIcons = !AppState.darkMode,
        maskBoxBackgroundColor = AppColors.background,
        includeStatusBarPadding = includeStatusBarPadding
    ) {
        Column(
            modifier = Modifier
                .weight(1f)
                .background(color = AppColors.background)
                .padding(horizontal = 16.dp)
        ) {

            val isNetworkAvailable = NetworkUtils.isNetworkAvailable(LocalContext.current)

            if (!isNetworkAvailable) {
                NetworkErrorContent(
                    onReload = {
                        LikeNoticeViewModel.reload(force = true)
                    }
                )
            } else if (likes.itemCount == 0) {
                Box(
                    modifier = Modifier.fillMaxSize()
                        .padding(top=149.dp),
                    contentAlignment = Alignment.TopCenter
                ) {
                    Column(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = R.mipmap.invalid_name_5),
                            contentDescription = "No Notice",
                            modifier = Modifier
                                .size(width = 181.dp, height = 153.dp)
                        )
                        Spacer(modifier = Modifier.height(9.dp))
                        Text(
                            text = stringResource(R.string.no_one_pinged_yet),
                            color = AppColors.text,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.W600,
                        )
                    }
                }
            }else{
                LazyColumn(
                    modifier = Modifier.weight(1f),
                    state = listState,
                ) {
                    items(likes.itemCount) {
                        val likeItem = likes[it]
                        if (likeItem != null) {
                            likeItem.post?.let { post ->
                                ActionPostNoticeItem(
                                    avatar = likeItem.user.avatar,
                                    nickName = likeItem.user.nickName,
                                    likeTime = likeItem.likeTime,
                                    thumbnail = post.images[0].thumbnail,
                                    action = "like",
                                    userId = likeItem.user.id,
                                    postId = post.id
                                )
                            }
                            likeItem.comment?.let { comment ->
                                LikeCommentNoticeItem(likeItem)
                            }
                        }
                    }
                    item {
                        BottomNavigationPlaceholder()
                    }
                }
            }

        }
    }
}

@Composable
fun ActionPostNoticeItem(
    avatar: String,
    nickName: String,
    likeTime: Date,
    thumbnail: String,
    action: String,
    userId: Int,
    postId: Int
) {
    val context = LocalContext.current
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current

    Box(
        modifier = Modifier.padding(vertical = 16.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.Top,
        ) {
            CustomAsyncImage(
                context,
                imageUrl = avatar,
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .noRippleClickable {
                        navController.navigate(
                            NavigationRoute.AccountProfile.route.replace(
                                "{id}",
                                userId.toString()
                            )
                        )
                    },
                contentDescription = action,
            )
            Spacer(modifier = Modifier.width(12.dp))
            Column(
                modifier = Modifier
                    .weight(1f)
                    .noRippleClickable {
                        navController.navigateToPost(
                            id = postId,
                            highlightCommentId = 0,
                            initImagePagerIndex = 0
                        )
                    }
            ) {
                Text(
                    text = nickName,
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp,
                    color = AppColors.text,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Spacer(modifier = Modifier.height(2.dp))
                when (action) {
                    "like" -> Text(stringResource(R.string.like_your_post), color = AppColors.text)
                    "favourite" -> Text(stringResource(R.string.favourite_your_post), color = AppColors.text)
                }
                Spacer(modifier = Modifier.height(2.dp))
                Row {
                    Text(likeTime.timeAgo(context), fontSize = 12.sp, color = AppColors.secondaryText)
                }
            }
            CustomAsyncImage(
                context,
                imageUrl = thumbnail,
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(8.dp)),
                contentDescription = action,
            )
        }
    }
}

@Composable
fun LikeCommentNoticeItem(
    item: AccountLikeEntity
) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val AppColors = LocalAppTheme.current

    Box(
        modifier = Modifier
            .padding(vertical = 16.dp)
            .noRippleClickable {
                item.comment?.postId.let {
                    navController.navigateToPost(
                        id = it ?: 0,
                        highlightCommentId = item.comment?.id ?: 0,
                        initImagePagerIndex = 0
                    )
                }
            }
    ) {
        Row {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.Top,
                ) {
                    CustomAsyncImage(
                        imageUrl = item.user.avatar,
                        modifier = Modifier
                            .size(48.dp)
                            .clip(CircleShape),
                        contentDescription = stringResource(R.string.like_your_comment)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Column(
                        modifier = Modifier
                            .weight(1f)
                    ) {
                        Text(
                            text = item.user.nickName,
                            fontWeight = FontWeight.Bold,
                            fontSize = 16.sp,
                            color = AppColors.text,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                        Spacer(modifier = Modifier.height(2.dp))
                        Text(stringResource(R.string.like_your_comment), color = AppColors.text)
                        Spacer(modifier = Modifier.height(2.dp))
                        Row {
                            Text(
                                item.likeTime.timeAgo(context),
                                fontSize = 12.sp,
                                color = AppColors.secondaryText
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.height(12.dp))
                Row(
                    modifier = Modifier.padding(start = 48.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(24.dp)
                            .background(Color.Gray.copy(alpha = 0.1f))
                    ) {
                        CustomAsyncImage(
                            context = context,
                            imageUrl = AppState.profile?.avatar ?: "",
                            contentDescription = "Comment Profile Picture",
                            modifier = Modifier
                                .size(24.dp)
                                .clip(RoundedCornerShape(24.dp)),
                            contentScale = ContentScale.Crop
                        )
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Column(
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = AppState.profile?.nickName ?: "",
                            fontWeight = FontWeight.W600,
                            fontSize = 14.sp,
                            color = AppColors.text
                        )
                        Text(
                            text = item.comment?.content ?: "",
                            fontSize = 12.sp,
                            color = AppColors.secondaryText,
                            maxLines = 2
                        )
                    }
                }
            }
            Spacer(modifier = Modifier.width(16.dp))
            if (item.comment?.replyComment?.post != null) {
                item.comment.replyComment.post.let {
                    CustomAsyncImage(
                        context = context,
                        imageUrl = it.images[0].thumbnail,
                        contentDescription = "Post Thumbnail",
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(8.dp)),
                        contentScale = ContentScale.Crop
                    )
                }
            } else {
                item.comment?.post?.let {
                    CustomAsyncImage(
                        context = context,
                        imageUrl = it.images[0].thumbnail,
                        contentDescription = "Post Thumbnail",
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(8.dp)),
                        contentScale = ContentScale.Crop
                    )
                }
            }


        }
    }
}