package com.aiosman.riderpro.ui.index.tabs.moment

import androidx.annotation.DrawableRes
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.defaultMinSize
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.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
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.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
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.rememberCoroutineScope
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.draw.shadow
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.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 androidx.paging.compose.collectAsLazyPagingItems
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.entity.MomentEntity
import com.aiosman.riderpro.entity.MomentImageEntity
import com.aiosman.riderpro.exp.timeAgo
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.comment.CommentModalContent
import com.aiosman.riderpro.ui.composables.AnimatedCounter
import com.aiosman.riderpro.ui.composables.AnimatedFavouriteIcon
import com.aiosman.riderpro.ui.composables.AnimatedLikeIcon
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.composables.RelPostCard
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.aiosman.riderpro.ui.navigateToPost
import com.aiosman.riderpro.ui.post.NewPostViewModel
import kotlinx.coroutines.launch

/**
 * 动态列表
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MomentsList() {
    val model = MomentViewModel
    var dataFlow = model.momentsFlow
    var moments = dataFlow.collectAsLazyPagingItems()
    val scope = rememberCoroutineScope()
    val state = rememberPullRefreshState(model.refreshing, onRefresh = {
        model.refreshPager(
            pullRefresh = true
        )
    })
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 48.dp
    val statusBarPaddingValues = WindowInsets.systemBars.asPaddingValues()
    LaunchedEffect(Unit) {
        model.refreshPager()
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(
                top = statusBarPaddingValues.calculateTopPadding(),
                bottom = navigationBarPaddings
            )
    ) {
        Box(Modifier.pullRefresh(state)) {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
            ) {
                items(
                    moments.itemCount,
                    key = { idx -> moments[idx]?.id ?: idx }
                ) { idx ->
                    val momentItem = moments[idx] ?: return@items
                    MomentCard(momentEntity = momentItem,
                        onAddComment = {
                            scope.launch {
                                model.onAddComment(momentItem.id)
                            }
                        },
                        onLikeClick = {
                            scope.launch {
                                if (momentItem.liked) {
                                    model.dislikeMoment(momentItem.id)
                                } else {
                                    model.likeMoment(momentItem.id)
                                }
                            }
                        },
                        onFavoriteClick = {
                            scope.launch {
                                if (momentItem.isFavorite) {
                                    model.unfavoriteMoment(momentItem.id)
                                } else {
                                    model.favoriteMoment(momentItem.id)
                                }
                            }
                        }
                    )
//                    Box(
//                        modifier = Modifier
//                            .height(4.dp)
//                            .fillMaxWidth()
//                            .background(Color(0xFFF0F2F5))
//                    )
                }
            }
            PullRefreshIndicator(model.refreshing, state, Modifier.align(Alignment.TopCenter))
        }
    }
}

@Composable
fun MomentCard(
    momentEntity: MomentEntity,
    onLikeClick: () -> Unit = {},
    onFavoriteClick: () -> Unit = {},
    onAddComment: () -> Unit = {},
    hideAction: Boolean = false
) {
    var imageIndex by remember { mutableStateOf(0) }
    val navController = LocalNavController.current
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        Box(
            modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp)
        ) {
            MomentTopRowGroup(momentEntity = momentEntity)
        }
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .noRippleClickable {
                    navController.navigateToPost(
                        momentEntity.id,
                        highlightCommentId = 0,
                        initImagePagerIndex = imageIndex
                    )
                }
        ) {
            MomentContentGroup(
                momentEntity = momentEntity,
                onPageChange = { index -> imageIndex = index }
            )
        }
        if (!hideAction) {
            MomentBottomOperateRowGroup(
                momentEntity = momentEntity,
                onLikeClick = onLikeClick,
                onAddComment = onAddComment,
                onShareClick = {
                    NewPostViewModel.asNewPost()
                    NewPostViewModel.relPostId = momentEntity.id
                    navController.navigate(NavigationRoute.NewPost.route)
                },
                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) {
    Text(
        modifier = Modifier,
        textAlign = TextAlign.Start,
        text = name,
        color = Color(0f, 0f, 0f),
        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) {
    Text(
        text = location,
        color = Color(0f, 0f, 0f, 0.6f),
        fontSize = 12.sp
    )
}

@Composable
fun MomentPostTime(time: String) {
    Text(
        modifier = Modifier,
        text = time, color = Color(0f, 0f, 0f, 0.6f),
        fontSize = 12.sp
    )
}

@Composable
fun MomentTopRowGroup(momentEntity: MomentEntity) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    Row(
        modifier = Modifier
    ) {
        CustomAsyncImage(
            context,
            momentEntity.avatar,
            contentDescription = "",
            modifier = Modifier
                .size(40.dp)
                .clip(RoundedCornerShape(40.dp))
                .noRippleClickable {
                    navController.navigate(
                        NavigationRoute.AccountProfile.route.replace(
                            "{id}",
                            momentEntity.authorId.toString()
                        )
                    )
                },
            contentScale = ContentScale.Crop
        )
        Column(
            modifier = Modifier
                .defaultMinSize()
                .padding(start = 12.dp, end = 12.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(22.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MomentName(momentEntity.nickname)
//                MomentFollowBtn()
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(21.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MomentPostTime(momentEntity.time.timeAgo(context))
                Spacer(modifier = Modifier.width(8.dp))
                MomentPostLocation(momentEntity.location)

            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class, ExperimentalSharedTransitionApi::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 = {}
) {
    if (momentEntity.momentTextContent.isNotEmpty()) {
        Text(
            text = momentEntity.momentTextContent,
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, end = 16.dp, bottom = 8.dp),
            fontSize = 16.sp
        )
    }
    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) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Image(
            modifier = Modifier
                .size(width = 24.dp, height = 24.dp),
            painter = painterResource(id = icon),
            contentDescription = ""
        )
        Text(
            text = count,
            modifier = Modifier.padding(start = 7.dp),
            fontSize = 12.sp,
        )
    }
}

@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 = {},
    onShareClick: () -> Unit = {},
    momentEntity: MomentEntity,
    imageIndex: Int = 0
) {
    val navController = LocalNavController.current
    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)
    ) {
        Row(
            modifier = Modifier.fillMaxSize()

        ) {
            Box(
                modifier = Modifier.fillMaxHeight(),
                contentAlignment = Alignment.Center
            ) {
                MomentOperateBtn(count = momentEntity.likeCount.toString()) {
                    AnimatedLikeIcon(
                        modifier = Modifier.size(24.dp),
                        liked = momentEntity.liked
                    ) {
                        onLikeClick()
                    }
                }
            }
            Spacer(modifier = Modifier.width(4.dp))
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .noRippleClickable {
                        onCommentClick()
                    },
                contentAlignment = Alignment.Center
            ) {
                MomentOperateBtn(
                    icon = R.drawable.rider_pro_comment,
                    count = momentEntity.commentCount.toString()
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight()
                    .noRippleClickable {
                        onFavoriteClick()
                    },
                contentAlignment = Alignment.CenterEnd
            ) {
                MomentOperateBtn(count = momentEntity.favoriteCount.toString()) {
                    AnimatedFavouriteIcon(
                        modifier = Modifier.size(24.dp),
                        isFavourite = momentEntity.isFavorite
                    ) {
                        onFavoriteClick()
                    }
                }
            }
        }
        if (momentEntity.images.size > 1) {
            Row(
                modifier = Modifier.fillMaxSize(),
                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))
                }
            }
        }


    }

}

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