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

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
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.Text
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.draw.alpha
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
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.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.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.nestedScroll
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.RoomEntity
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToGroupChat
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.data.api.ApiClient
import android.util.Base64
import com.aiosman.ravenow.ui.network.ReloadButton
import com.aiosman.ravenow.utils.NetworkUtils.isNetworkAvailable

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun GroupChatEmptyContent(
    modifier: Modifier = Modifier,
    listState: LazyListState,
    nestedScrollConnection: NestedScrollConnection? = null,
    ownerSessionId: String? = null, // 创建者用户ID（ChatAIID），用于过滤特定创建者的房间。如果为null，则显示当前用户创建或加入的房间
    showSegments: Boolean = true // 是否显示分段控制器（全部、公开、私有）
) {
    var selectedSegment by remember { mutableStateOf(0) } // 0: 全部, 1: 公开, 2: 私有
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val navController = LocalNavController.current
    val viewModel = MyProfileViewModel
    val networkAvailable = isNetworkAvailable(context)
    
    // 如果查看其他用户的房间，固定使用全部类型（filterType = 0）
    val filterType = if (showSegments) selectedSegment else 0
    
    val state = rememberPullRefreshState(
        refreshing = viewModel.roomsRefreshing,
        onRefresh = {
            viewModel.refreshRooms(filterType = filterType, ownerSessionId = ownerSessionId)
        }
    )
    
    // 当分段或用户ID改变时，重新加载数据
    LaunchedEffect(selectedSegment, ownerSessionId, showSegments) {
        viewModel.refreshRooms(filterType = filterType, ownerSessionId = ownerSessionId)
    }
    
    val nestedScrollModifier = if (nestedScrollConnection != null) {
        Modifier.nestedScroll(nestedScrollConnection)
    } else {
        Modifier
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp)
    ) {
        Spacer(modifier = Modifier.height(16.dp))
        
        // 只在查看自己的房间时显示分段控制器
        if (showSegments) {
            SegmentedControl(
                selectedIndex = selectedSegment,
                onSegmentSelected = { 
                    selectedSegment = it
                    // LaunchedEffect 会监听 selectedSegment 的变化并自动刷新
                },
                modifier = Modifier.fillMaxWidth()
            )
            
            Spacer(modifier = Modifier.height(8.dp))
        }
        
        Box(
            modifier = nestedScrollModifier
                .fillMaxSize()
                .pullRefresh(state)
        ) {
            if (viewModel.rooms.isEmpty() && !viewModel.roomsLoading) {
                // 空状态内容（居中）
                Column(
                    modifier = nestedScrollModifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 空状态插图
                    EmptyStateIllustration(
                        isNetworkAvailable = networkAvailable,
                        onReload = {
                            MyProfileViewModel.ResetModel()
                            MyProfileViewModel.loadProfile(pullRefresh = true)
                        }
                    )
                    
                    Spacer(modifier = Modifier.height(9.dp))
                    
                    // 网络可用时才展示空状态文本
                    if (networkAvailable) {
                        Text(
                            text = stringResource(R.string.cosmos_awaits),
                            fontSize = 16.sp,
                            fontWeight = FontWeight.SemiBold,
                            color = AppColors.text,
                            textAlign = TextAlign.Center,
                            modifier = Modifier.padding(horizontal = 24.dp),
                            maxLines = 2,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            } else {
                LazyColumn(
                    state = listState,
                    modifier = nestedScrollModifier.fillMaxSize()
                ) {
                    // 网格布局：每行显示2个房间卡片
                    items(
                        items = viewModel.rooms.chunked(2),
                        key = { rowRooms -> rowRooms.firstOrNull()?.id?.toString() ?: "" }
                    ) { rowRooms ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 12.dp),
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            rowRooms.forEach { room ->
                                RoomCard(
                                    room = room,
                                    onRoomClick = { roomEntity ->
                                        // 导航到群聊聊天界面
                                        navController.navigateToGroupChat(
                                            id = roomEntity.trtcRoomId,
                                            name = roomEntity.name,
                                            avatar = roomEntity.avatar
                                        )
                                    },
                                    modifier = Modifier.weight(1f)
                                )
                            }
                            // 如果这一行只有一个房间，添加一个空的占位符
                            if (rowRooms.size == 1) {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }
                    }
                    
                    // 加载更多指示器
                    if (viewModel.roomsLoading && viewModel.rooms.isNotEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                LottieAnimation(
                                    composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                                    iterations = LottieConstants.IterateForever,
                                    modifier = Modifier.size(80.dp)
                                )
                            }
                        }
                    }
                    
                    // 加载更多触发
                    if (viewModel.roomsHasMore && !viewModel.roomsLoading) {
                        item {
                            LaunchedEffect(Unit) {
                                viewModel.loadMoreRooms(filterType = filterType, ownerSessionId = ownerSessionId)
                            }
                        }
                    }
                }
            }
            
            PullRefreshIndicator(
                refreshing = viewModel.roomsRefreshing,
                state = state,
                modifier = Modifier.align(Alignment.TopCenter)
            )
        }
    }
}

@Composable
fun RoomCard(
    room: RoomEntity,
    onRoomClick: (RoomEntity) -> Unit = {},
    modifier: Modifier = Modifier
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val roomDebouncer = rememberDebouncer()
    val cardSize = 180.dp
    
    // 构建头像URL
    val avatarUrl = if (room.avatar.isNotEmpty()) {
        "${ConstVars.BASE_SERVER}/api/v1/outside/${room.avatar}?token=${AppStore.token}"
    } else {
        // 如果头像为空，使用群头像接口
        val groupIdBase64 = Base64.encodeToString(
            room.trtcType.toByteArray(),
            Base64.NO_WRAP
        )
        "${ApiClient.RETROFIT_URL}group/avatar?groupIdBase64=${groupIdBase64}&token=${AppStore.token}"
    }
    
    // 优先显示cover，如果没有cover则显示recommendBanner，最后显示avatar
    val imageUrl = when {
        room.cover.isNotEmpty() -> "${ConstVars.BASE_SERVER}/api/v1/outside/${room.cover}?token=${AppStore.token}"
        room.recommendBanner.isNotEmpty() -> "${ConstVars.BASE_SERVER}/api/v1/outside/${room.recommendBanner}?token=${AppStore.token}"
        else -> avatarUrl
    }
    
    // 正方形卡片，文字重叠在底部
    Box(
        modifier = modifier
            .size(cardSize)
            .background(AppColors.tabUnselectedBackground, RoundedCornerShape(12.dp))
            .noRippleClickable {
                roomDebouncer {
                    onRoomClick(room)
                }
            }
    ) {
        CustomAsyncImage(
            context = context,
            imageUrl = imageUrl,
            contentDescription = room.name,
            modifier = Modifier
                .width(cardSize)
                .height(120.dp)
                .clip(RoundedCornerShape(
                    topStart = 12.dp,
                    topEnd = 12.dp,
                    bottomStart = 0.dp,
                    bottomEnd = 0.dp)),
            contentScale = ContentScale.Crop,
            defaultRes = R.mipmap.rider_pro_agent
        )
        
        // 房间名称，重叠在底部
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .padding(bottom = 32.dp, start = 10.dp, end = 10.dp)
                .clip(RoundedCornerShape(12.dp))
        ) {
            Text(
                text = room.name,
                fontSize = 14.sp,
                fontWeight = FontWeight.W900,
                color = AppColors.text,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Left
            )
        }
        
        // 显示人数
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .padding(bottom = 10.dp, start = 10.dp, end = 10.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                Image(
                    painter = painterResource(R.drawable.rider_pro_nav_profile),
                    contentDescription = "chat",
                    modifier = Modifier.size(16.dp),
                    colorFilter = ColorFilter.tint(AppColors.secondaryText)
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text(
                    text = "${room.userCount} ${stringResource(R.string.chatting_now)}",
                    fontSize = 12.sp,
                    modifier = Modifier
                        .alpha(0.6f)
                        .weight(1f),
                    color = AppColors.text,
                    fontWeight = FontWeight.W500,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

/**
 * 列表样式的房间项，供搜索等场景复用
 */
@Composable
fun RoomItem(
    room: RoomEntity,
    onRoomClick: (RoomEntity) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val roomDebouncer = rememberDebouncer()

    // 构建头像URL
    val avatarUrl = if (room.avatar.isNotEmpty()) {
        "${ConstVars.BASE_SERVER}/api/v1/outside/${room.avatar}?token=${AppStore.token}"
    } else {
        val groupIdBase64 = Base64.encodeToString(
            room.trtcType.toByteArray(),
            Base64.NO_WRAP
        )
        "${ApiClient.RETROFIT_URL}group/avatar?groupIdBase64=${groupIdBase64}&token=${AppStore.token}"
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 12.dp)
            .noRippleClickable {
                roomDebouncer {
                    onRoomClick(room)
                }
            }
    ) {
        Box {
            CustomAsyncImage(
                context = context,
                imageUrl = avatarUrl,
                contentDescription = room.name,
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(12.dp))
            )
        }

        Column(
            modifier = Modifier
                .weight(1f)
                .padding(start = 12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = room.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.text,
                    modifier = Modifier.weight(1f),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }

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

            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = room.description.ifEmpty { "暂无描述" },
                    fontSize = 14.sp,
                    color = AppColors.secondaryText,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f)
                )

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

                Text(
                    text = "${room.userCount}人",
                    fontSize = 12.sp,
                    color = AppColors.secondaryText
                )
            }
        }
    }
}

@Composable
private fun SegmentedControl(
    selectedIndex: Int,
    onSegmentSelected: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    val AppColors = LocalAppTheme.current
    Row(
        modifier = modifier
            .height(32.dp),
        horizontalArrangement = Arrangement.Start,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 全部
        SegmentButton(
            text = stringResource(R.string.chat_all),
            isSelected = selectedIndex == 0,
            onClick = { onSegmentSelected(0) },
            width = 54.dp,
            appColors = AppColors
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 公开
        SegmentButton(
            text = stringResource(R.string.public_label),
            isSelected = selectedIndex == 1,
            onClick = { onSegmentSelected(1) },
            width = 59.dp,
            appColors = AppColors
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 私有
        SegmentButton(
            text = stringResource(R.string.private_label),
            isSelected = selectedIndex == 2,
            onClick = { onSegmentSelected(2) },
            width = 54.dp,
            appColors = AppColors
        )
    }
}

@Composable
private fun SegmentButton(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    width: androidx.compose.ui.unit.Dp,
    appColors: com.aiosman.ravenow.AppThemeData
) {
    Box(
        modifier = Modifier
            .width(width)
            .height(32.dp)
            .background(
                color = if (isSelected) {
                    appColors.checkedBackground // 使用选中背景色（暗色模式下是白色，亮色模式下是黑色）
                } else {
                    Color(0x147C7480) // RGB(124, 116, 128, alpha 0.08)
                },
                shape = RoundedCornerShape(1000.dp)
            )
            .noRippleClickable { onClick() },
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            fontSize = 13.sp,
            fontWeight = FontWeight.Normal,
            color = if (isSelected) {
                appColors.checkedText // 选中时使用选中文本颜色（暗色模式下是黑色，亮色模式下是白色）
            } else {
                appColors.text // 未选中时使用文本颜色
            }
        )
    }
}

@Composable
private fun EmptyStateIllustration(
    isNetworkAvailable: Boolean,
    onReload: () -> Unit
) {
    val AppColors = LocalAppTheme.current
    if (isNetworkAvailable) {
        Image(
            painter = painterResource(id = R.mipmap.l_empty_img),
            contentDescription = "空状态",
            modifier = Modifier
                .width(181.dp)
                .height(153.dp),
            contentScale = ContentScale.Fit
        )
    } else {
        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 = onReload)
    }
}

