package com.aiosman.ravenow.ui.composables

import androidx.annotation.DrawableRes
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
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.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
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.layout.wrapContentWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
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.MomentEntity
import com.aiosman.ravenow.entity.MomentImageEntity
import com.aiosman.ravenow.exp.timeAgo
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.comment.CommentModalContent
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost

@Composable
fun MomentCard(
    modifier: Modifier = Modifier,
    momentEntity: MomentEntity,
    onLikeClick: () -> Unit = {},
    onFavoriteClick: () -> Unit = {},
    onAddComment: () -> Unit = {},
    onFollowClick: () -> Unit = {},
    hideAction: Boolean = false,
    showFollowButton: Boolean = true
) {
    val AppColors = LocalAppTheme.current
    var imageIndex by remember { mutableStateOf(0) }
    val navController = LocalNavController.current
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(AppColors.background)
    ) {
        Box(
            modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp)
        ) {
            MomentTopRowGroup(
                momentEntity = momentEntity,
                onFollowClick = onFollowClick,
                showFollowButton = showFollowButton
            )
        }
        val lastClickTime = remember { mutableStateOf(0L) }
        val clickDelay = 500L
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .noRippleClickable {
                    val currentTime = System.currentTimeMillis()
                    if (currentTime - lastClickTime.value > clickDelay) {
                        lastClickTime.value = currentTime
                        navController.navigateToPost(
                            momentEntity.id,
                            highlightCommentId = 0,
                            initImagePagerIndex = imageIndex
                        )
                    }
                }
        ) {
            MomentContentGroup(
                momentEntity = momentEntity,
                onPageChange = { index -> imageIndex = index }
            )
        }
        if (!hideAction) {
            MomentBottomOperateRowGroup(
                momentEntity = momentEntity,
                onLikeClick = onLikeClick,
                onAddComment = onAddComment,
                onFavoriteClick = onFavoriteClick,
                imageIndex = imageIndex,
                onCommentClick = {
                    navController.navigateToPost(
                        momentEntity.id,
                        highlightCommentId = 0,
                        initImagePagerIndex = imageIndex
                    )
                }
            )
        }
    }
}

@Composable
fun ModificationListHeader() {
    val navController = LocalNavController.current
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color(0xFFF8F8F8))
                .padding(4.dp)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    navController.navigate("ModificationList")
                }
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Box(
                    modifier = Modifier
                        .background(Color(0xFFEB4869))
                        .padding(8.dp)
                ) {
                    Icon(
                        Icons.Filled.Build,
                        contentDescription = "Modification Icon",
                        tint = Color.White, // Assuming the icon should be white
                        modifier = Modifier.size(12.dp)
                    )
                }
                Spacer(modifier = Modifier.width(12.dp))
                Text(
                    text = "Modification List",
                    color = Color(0xFF333333),
                    fontSize = 14.sp,
                    textAlign = TextAlign.Left
                )
            }
        }
    }
}

@Composable
fun MomentName(name: String, modifier: Modifier = Modifier) {
    val AppColors = LocalAppTheme.current
    Text(
        modifier = modifier,
        textAlign = TextAlign.Start,
        text = name,
        color = AppColors.text,
        fontSize = 16.sp, style = TextStyle(fontWeight = FontWeight.Bold)
    )
}

@Composable
fun MomentFollowBtn() {
    Box(
        modifier = Modifier
            .size(width = 53.dp, height = 18.dp)
            .padding(start = 8.dp),
        contentAlignment = Alignment.Center
    ) {
        Image(
            modifier = Modifier
                .fillMaxSize(),
            painter = painterResource(id = R.drawable.follow_bg),
            contentDescription = ""
        )
        Text(
            text = "Follow",
            color = Color.White,
            fontSize = 12.sp
        )
    }
}

@Composable
fun MomentPostLocation(location: String) {
    val AppColors = LocalAppTheme.current
    Text(
        text = location,
        color = AppColors.secondaryText,
        fontSize = 12.sp,
        )
}

@Composable
fun MomentPostTime(time: String) {
    val AppColors = LocalAppTheme.current
    Text(
        modifier = Modifier,
        text = time, color = AppColors.text,
        fontSize = 12.sp
    )
}

@Composable
fun MomentTopRowGroup(
    momentEntity: MomentEntity,
    showFollowButton: Boolean = true,
    onFollowClick: () -> Unit = {}
) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    Row(
        modifier = Modifier
    ) {
        val lastClickTime = remember { mutableStateOf(0L) }
        val clickDelay = 500L
        CustomAsyncImage(
            context,
            momentEntity.avatar,
            contentDescription = "",
            modifier = Modifier
                .size(40.dp)
                .clip(RoundedCornerShape(40.dp))
                .noRippleClickable {
                    val currentTime = System.currentTimeMillis()
                    if (currentTime - lastClickTime.value > clickDelay) {
                        lastClickTime.value = currentTime
                        navController.navigate(
                            NavigationRoute.AccountProfile.route.replace(
                                "{id}",
                                momentEntity.authorId.toString()
                            )
                        )
                    }
                },
            contentScale = ContentScale.Crop
        )
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(start = 12.dp, end = 12.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(22.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MomentName(
                    modifier = Modifier.weight(1f)
                        .noRippleClickable {
                            val currentTime = System.currentTimeMillis()
                            if (currentTime - lastClickTime.value > clickDelay) {
                                lastClickTime.value = currentTime
                                navController.navigate(
                                    NavigationRoute.AccountProfile.route.replace(
                                        "{id}",
                                        momentEntity.authorId.toString()
                                    )
                                )
                            }
                        },
                    name = momentEntity.nickname
                )
                Spacer(modifier = Modifier.width(16.dp))

            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(21.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MomentPostTime(momentEntity.time.timeAgo(context))
                Spacer(modifier = Modifier.width(8.dp))
                //MomentPostLocation(momentEntity.location)
            }
        }
        val isFollowing = momentEntity.followStatus
        if (showFollowButton && !isFollowing) {
            Spacer(modifier = Modifier.width(16.dp))
            if (AppState.UserId != momentEntity.authorId) {
                FollowButton(
                    isFollowing = false
                ) {
                    onFollowClick()
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PostImageView(
    images: List<MomentImageEntity>,
    onPageChange: (Int) -> Unit = {}
) {
    val pagerState = rememberPagerState(pageCount = { images.size })
    LaunchedEffect(pagerState.currentPage) {
        onPageChange(pagerState.currentPage)
    }
    val context = LocalContext.current

    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        HorizontalPager(
            state = pagerState,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(1f),
        ) { page ->
            val image = images[page]
            CustomAsyncImage(
                context,
                image.thumbnail,
                contentDescription = "Image",
                blurHash = image.blurHash,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .fillMaxSize()
            )

        }
    }

}

@Composable
fun MomentContentGroup(
    momentEntity: MomentEntity,
    onPageChange: (Int) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    if (momentEntity.momentTextContent.isNotEmpty()) {
        Text(
            text = momentEntity.momentTextContent,
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, end = 16.dp, bottom = 8.dp),
            fontSize = 16.sp,
            color = AppColors.text
        )
    }
    if (momentEntity.relMoment != null) {
        RelPostCard(
            momentEntity = momentEntity.relMoment!!,
            modifier = Modifier.background(Color(0xFFF8F8F8))
        )
    } else {
        Box(
            modifier = Modifier.fillMaxWidth()
        ) {
            PostImageView(
                images = momentEntity.images,
                onPageChange = onPageChange
            )
        }
    }

}

@Composable
fun MomentOperateBtn(@DrawableRes icon: Int, count: String) {
    val AppColors = LocalAppTheme.current
    Row(verticalAlignment = Alignment.CenterVertically) {
        Image(
            modifier = Modifier
                .size(width = 24.dp, height = 24.dp),
            painter = painterResource(id = icon),
            contentDescription = "",
            colorFilter = ColorFilter.tint(AppColors.text)
        )
        Text(
            text = count,
            modifier = Modifier.padding(start = 7.dp),
            fontSize = 14.sp,
            color = AppColors.text
        )
    }
}

@Composable
fun MomentOperateBtn(count: String, content: @Composable () -> Unit) {
    Row(
        modifier = Modifier,
        verticalAlignment = Alignment.CenterVertically
    ) {
        content()
        AnimatedCounter(
            count = count.toInt(),
            fontSize = 14,
            modifier = Modifier
                .padding(start = 7.dp)
                .width(24.dp)
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MomentBottomOperateRowGroup(
    onLikeClick: () -> Unit = {},
    onAddComment: () -> Unit = {},
    onCommentClick: () -> Unit = {},
    onFavoriteClick: () -> Unit = {},
    momentEntity: MomentEntity,
    imageIndex: Int = 0
) {
    val lastClickTime = remember { mutableStateOf(0L) }
    val clickDelay = 500L
    var showCommentModal by remember { mutableStateOf(false) }
    if (showCommentModal) {
        ModalBottomSheet(
            onDismissRequest = { showCommentModal = false },
            containerColor = Color.White,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            windowInsets = WindowInsets(0),
            dragHandle = {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.dp)
                        .clip(CircleShape)
                ) {

                }
            }
        ) {
            CommentModalContent(
                postId = momentEntity.id,
                commentCount = momentEntity.commentCount,
                onCommentAdded = {
                    onAddComment()
                }
            )
        }
    }
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(56.dp)
            .padding(start = 16.dp, end = 0.dp)
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            if (momentEntity.images.size > 1) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    momentEntity.images.forEachIndexed { index, _ ->
                        Box(
                            modifier = Modifier
                                .size(4.dp)
                                .clip(CircleShape)
                                .background(
                                    if (imageIndex == index) Color.Red else Color.Gray.copy(
                                        alpha = 0.5f
                                    )
                                )
                                .padding(1.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                    }
                }
            }

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxHeight(),
                    contentAlignment = Alignment.CenterStart
                ) {
                    MomentOperateBtn(count = momentEntity.favoriteCount.toString()) {
                        AnimatedFavouriteIcon(
                            modifier = Modifier.size(24.dp),
                            isFavourite = momentEntity.isFavorite
                        ) {
                            onFavoriteClick()
                        }
                    }
                }

                Box(
                    modifier = Modifier
                        .wrapContentWidth()
                        .fillMaxHeight()
                        .noRippleClickable {
                            val currentTime = System.currentTimeMillis()
                            if (currentTime - lastClickTime.value > clickDelay) {
                                lastClickTime.value = currentTime
                                onCommentClick()
                            }
                        },
                    contentAlignment = Alignment.CenterEnd
                ) {
                    MomentOperateBtn(
                        icon = R.drawable.rider_pro_comment,
                        count = momentEntity.commentCount.toString()
                    )
                }

                Spacer(modifier = Modifier.width(24.dp))

                Box(
                    modifier = Modifier
                        .wrapContentWidth()
                        .fillMaxHeight(),
                    contentAlignment = Alignment.CenterEnd
                ) {
                    MomentOperateBtn(count = momentEntity.likeCount.toString()) {
                        AnimatedLikeIcon(
                            modifier = Modifier.size(24.dp),
                            liked = momentEntity.liked
                        ) {
                            onLikeClick()
                        }
                    }
                }
            }
        }
    }


}

@Composable
fun MomentListLoading() {
    CircularProgressIndicator(
        modifier =
            Modifier
                .fillMaxWidth()
                .wrapContentWidth(Alignment.CenterHorizontally),
        color = Color.Red
    )
}