package com.aiosman.ravenow.ui.index.tabs.profile.composable

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.Spacer
import androidx.compose.foundation.layout.aspectRatio
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.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.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.unit.dp
import androidx.compose.ui.unit.sp
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.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.ravenow.ui.network.ReloadButton
import com.aiosman.ravenow.utils.NetworkUtils
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.nestedScroll
@Composable
fun GalleryItem(
    moment: MomentEntity,
    idx: Int = 0
) {
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current
    val debouncer = rememberDebouncer()

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .let {
                val firstImage = moment.images.firstOrNull()
                if (firstImage?.width != null &&
                    firstImage.height != null &&
                    firstImage.width!! > 0 &&
                    firstImage.height!! > 0
                ) {
                    val ratio = firstImage.width!!.toFloat() / firstImage.height!!.toFloat()
                    return@let it.aspectRatio(ratio.coerceIn(0.7f, 1.5f))
                } else {
                    return@let it.aspectRatio(if (idx % 3 == 0) 1.5f else 1f)
                }
            }
            .clip(RoundedCornerShape(8.dp))
            .noRippleClickable {
                debouncer {
                    navController.navigateToPost(
                        moment.id
                    )
                }
            }
    ) {
        // 检查图片列表是否为空
        if (moment.images.isEmpty()) {
            // 显示占位符内容，类似于EmptyAgentsView
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 60.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Image(
                    painter = painterResource(R.mipmap.qs_dt_qs_img),
                    contentDescription = "暂无图片",
                    modifier = Modifier.size(181.dp),
                )

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

                Text(
                    text = "故事还没开始",
                    fontSize = 16.sp,
                    color = AppColors.text,
                    fontWeight = FontWeight.W600
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "发布一条动态，和世界打个招呼吧",
                    fontSize = 14.sp,
                    color = AppColors.secondaryText,
                    fontWeight = FontWeight.W400
                )
            }
        } else {
            CustomAsyncImage(
                LocalContext.current,
                moment.images[0].thumbnail,
                modifier = Modifier
                    .fillMaxSize(),
                contentDescription = "",
                contentScale = ContentScale.Crop,
            )
        }
    }
}


@Composable
fun GalleryGrid(
    moments: List<MomentEntity>,
    modifier: Modifier = Modifier,
    state: LazyGridState,
    nestedScrollConnection: NestedScrollConnection? = null
) {
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current
    val debouncer = rememberDebouncer()
    var refreshKey by remember { mutableStateOf(0) }
    val isNetworkAvailable = NetworkUtils.isNetworkAvailable(LocalContext.current)
    val baseModifier = if (nestedScrollConnection != null) {
        modifier.nestedScroll(nestedScrollConnection)
    } else {
        modifier
    }

    if (!isNetworkAvailable) {
        Column(
            modifier = baseModifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(vertical = 60.dp)
                .padding(horizontal = 16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(
                painter = painterResource(id = R.mipmap.invalid_name_10),
                contentDescription = "network error",
                modifier = Modifier.size(181.dp),
            )

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

            Text(
                text = stringResource(R.string.friend_chat_no_network_title),
                fontSize = 16.sp,
                color = AppColors.text,
                fontWeight = FontWeight.W600
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = stringResource(R.string.friend_chat_no_network_subtitle),
                fontSize = 14.sp,
                color = AppColors.secondaryText,
                fontWeight = FontWeight.W400
            )
            Spacer(modifier = Modifier.height(16.dp))
            ReloadButton(
                onClick = {
                    refreshKey++
                    MyProfileViewModel.ResetModel()
                    MyProfileViewModel.loadProfile(pullRefresh = true)
                }
            )
        }
    } else if (moments.isEmpty()) {
        Column(
            modifier = baseModifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(vertical = 60.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(
                painter = painterResource(id = R.mipmap.l_empty_img),
                contentDescription = "暂无图片",
                modifier = Modifier
                    .size(width = 181.dp, height = 153.dp),
            )

            Spacer(modifier = Modifier.height(9.dp))

            Text(
                text = stringResource(R.string.cosmos_awaits),
                fontSize = 16.sp,
                color = AppColors.text,
                fontWeight = FontWeight.W600,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(horizontal = 24.dp),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
        }
    } else {
        LazyVerticalGrid(
            columns = GridCells.Fixed(3),
            state = state,
            modifier = baseModifier
                .fillMaxSize()
                .padding(bottom = 8.dp),
        ) {
            itemsIndexed(moments) { idx, moment ->
                moment?.let { momentItem ->
                    val itemDebouncer = rememberDebouncer()
                    val isVideoMoment = momentItem.images.isEmpty() && !momentItem.videos.isNullOrEmpty()
                    val previewUrl = when {
                        momentItem.images.isNotEmpty() -> momentItem.images[0].thumbnail
                        isVideoMoment -> {
                            val firstVideo = momentItem.videos!!.first()
                            firstVideo.thumbnailDirectUrl
                                ?: firstVideo.thumbnailUrl
                                ?: firstVideo.directUrl
                                ?: firstVideo.url
                        }
                        else -> null
                    }
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .padding(2.dp)
                            .noRippleClickable {
                                itemDebouncer {
                                    navController.navigateToPost(
                                        id = momentItem.id,
                                        highlightCommentId = 0,
                                        initImagePagerIndex = 0
                                    )
                                }
                            }
                    ) {
                        if (previewUrl != null) {
                            CustomAsyncImage(
                                imageUrl = previewUrl,
                                contentDescription = "",
                                modifier = Modifier.fillMaxSize(),
                                context = LocalContext.current
                            )
                        } else {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .background(
                                        color = AppColors.basicMain.copy(alpha = 0.2f),
                                        shape = RoundedCornerShape(10.dp)
                                    )
                            )
                        }
                    }
                }
            }
            item {
                Spacer(modifier = Modifier.height(120.dp))
            }
        }
    }
}


