package com.aiosman.ravenow.ui.group

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.zIndex
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.GroupMember
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToAddGroupMember

@Composable
fun GroupMembersScreen(groupId: String) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val AppColors = LocalAppTheme.current
    
    val viewModel = viewModel<GroupMembersViewModel>(
        key = "GroupMembersViewModel_$groupId",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return GroupMembersViewModel(groupId) as T
            }
        }
    )
    
    var selectedMemberPosition by remember { mutableStateOf<Pair<Offset, Float>?>(null) }
    var selectedMemberId by remember { mutableStateOf<String?>(null) }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            // 顶部导航栏
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(AppColors.background)
            ) {
                StatusBarSpacer()
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 12.dp, horizontal = 12.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    androidx.compose.foundation.Image(
                        painter = painterResource(R.drawable.rider_pro_back_icon),
                        contentDescription = null,
                        colorFilter = ColorFilter.tint(AppColors.text),
                        modifier = Modifier
                            .size(24.dp)
                            .noRippleClickable {
                                navController.navigateUp()
                            }
                    )
                    
                    Text(
                        text = stringResource(R.string.group_members_title),
                        style = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text,
                            fontSize = 17.sp,
                            fontWeight = FontWeight.SemiBold
                        ),
                        modifier = Modifier.weight(1f),
                        textAlign = TextAlign.Center
                    )
                    
//                    androidx.compose.foundation.Image(
//                        painter = painterResource(R.drawable.rider_pro_add_other),
//                        contentDescription = stringResource(R.string.group_chat_info_add_member),
//                        colorFilter = ColorFilter.tint(AppColors.text),
//                        modifier = Modifier
//                            .size(24.dp)
//                            .noRippleClickable {
//                                navController.navigateToAddGroupMember(groupId, viewModel.groupInfo?.groupName)
//                            }
//                    )
                }
            }
            
            // 内容区域
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),
                verticalArrangement = Arrangement.spacedBy(0.dp)
            ) {
            // 当前用户信息
            item {
                if (viewModel.currentUserMember != null) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = stringResource(R.string.group_members_you),
                        style = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text.copy(alpha = 0.6f),
                            fontSize = 13.sp
                        ),
                        modifier = Modifier.padding(start = 12.dp, bottom = 8.dp)
                    )
                    CurrentUserItem(
                        member = viewModel.currentUserMember!!,
                        isAdmin = viewModel.groupInfo?.isCreator == true
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                }
            }
            
            // 群成员列表
            item {
                Text(
                    text = stringResource(
                        R.string.group_members_list,
                        viewModel.members.size + (if (viewModel.currentUserMember != null) 1 else 0)
                    ),
                    style = androidx.compose.ui.text.TextStyle(
                        color = AppColors.text.copy(alpha = 0.6f),
                        fontSize = 13.sp
                    ),
                    modifier = Modifier.padding()
                )
            }
            
                items(viewModel.members) { member ->
                    MemberItem(
                        member = member,
                        isAdmin = viewModel.groupInfo?.isCreator == true,
                        onSendMessage = {
                            // TODO: 实现发消息功能
                        },
                        onMenuClick = { position, height ->
                            if (selectedMemberId == member.userId) {
                                selectedMemberId = null
                                selectedMemberPosition = null
                            } else {
                                selectedMemberId = member.userId
                                selectedMemberPosition = Pair(position, height)
                            }
                        },
                        onDeleteMember = {
                            viewModel.deleteMember(member.userId)
                            selectedMemberId = null
                            selectedMemberPosition = null
                        },
                        isMenuVisible = selectedMemberId == member.userId
                    )
                }
            }
        }
        
        // 弹窗 - 显示在最上层
        selectedMemberPosition?.let { (position, height) ->
            val configuration = LocalConfiguration.current
            val density = LocalDensity.current
            val screenWidth = with(density) { configuration.screenWidthDp.dp }
            val horizontalOffset = (screenWidth - 238.dp) / 2
            
            Box(
                modifier = Modifier
                    .width(238.dp)
                    .height(60.dp)
                    .zIndex(1000f)
                    .offset {
                        val xOffset = with(density) { horizontalOffset.toPx().toInt() }
                        val yOffset = (position.y + height + with(density) { 4.dp.toPx() }).toInt()
                        IntOffset(x = xOffset, y = yOffset)
                    }
                    .shadow(
                        elevation = 8.dp,
                        shape = RoundedCornerShape(24.dp),
                        spotColor = Color.Black.copy(alpha = 0.15f),
                        ambientColor = Color.Black.copy(alpha = 0.08f)
                    )
                    .clip(RoundedCornerShape(24.dp))
                    .background(
                        brush = androidx.compose.ui.graphics.Brush.verticalGradient(
                            colors = listOf(
                                Color(0xFF262626).copy(alpha = 0.4f),
                                Color(0xFFF5F5F5).copy(alpha = 0.6f)
                            )
                        )
                    )
                    .clickable {
                        selectedMemberId?.let { memberId ->
                            viewModel.deleteMember(memberId)
                            selectedMemberId = null
                            selectedMemberPosition = null
                        }
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.group_members_delete_member),
                    color = Color(0xFFFF3B30),
                    fontSize = 15.sp
                )
            }
        }
    }
}

@Composable
private fun CurrentUserItem(
    member: GroupMember,
    isAdmin: Boolean
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 头像
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(
                    if (member.avatar.isNotEmpty()) Color.Transparent
                    else AppColors.decentBackground
                )
        ) {
            if (member.avatar.isNotEmpty()) {
                CustomAsyncImage(
                    imageUrl = member.avatar,
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(CircleShape),
                    contentDescription = member.nickname
                )
            } else {
                // 默认头像占位
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color(0xFFF0EEF1)),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        painter = painterResource(R.drawable.default_avatar),
                        contentDescription = null,
                        tint = AppColors.text.copy(alpha = 0.5f),
                        modifier = Modifier.size(20.dp)
                    )
                }
            }
        }
        
        Spacer(modifier = Modifier.width(12.dp))
        
        // 名称和身份
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = member.nickname,
                style = androidx.compose.ui.text.TextStyle(
                    color = AppColors.text,
                    fontSize = 13.sp,
                    fontWeight = FontWeight.Medium
                )
            )
            if (isAdmin) {
                Spacer(modifier = Modifier.height(2.dp))
                Text(
                    text = stringResource(R.string.group_members_admin),
                    style = androidx.compose.ui.text.TextStyle(
                        color = AppColors.text,
                        fontSize = 12.sp
                    )
                )
            }
        }
    }
}

@Composable
private fun MemberItem(
    member: GroupMember,
    isAdmin: Boolean,
    onSendMessage: () -> Unit,
    onMenuClick: (Offset, Float) -> Unit,
    onDeleteMember: () -> Unit,
    isMenuVisible: Boolean
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val density = LocalDensity.current
    var itemPosition by remember { mutableStateOf(Offset.Zero) }
    var itemHeight by remember { mutableStateOf(0f) }
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
            .onGloballyPositioned { coordinates ->
                itemPosition = coordinates.positionInRoot()
                itemHeight = coordinates.size.height.toFloat()
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
            // 头像
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(
                        if (member.avatar.isNotEmpty()) Color.Transparent
                        else AppColors.decentBackground
                    )
            ) {
                if (member.avatar.isNotEmpty()) {
                    CustomAsyncImage(
                        imageUrl = member.avatar,
                        modifier = Modifier
                            .fillMaxSize()
                            .clip(CircleShape),
                        contentDescription = member.nickname
                    )
                } else {
                    // 默认头像占位
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color(0xFFF0EEF1)),
                        contentAlignment = Alignment.Center
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.group_copy),
                            contentDescription = "默认头像",
                            modifier = Modifier.size(40.dp),
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 名称
            Text(
                text = member.nickname,
                style = androidx.compose.ui.text.TextStyle(
                    color = AppColors.text,
                    fontSize = 13.sp,
                    fontWeight = FontWeight.Medium
                )
            )
            Spacer(modifier = Modifier.weight(1f))
            
        // 菜单按钮
        if (isAdmin) {
            IconButton(
                onClick = { onMenuClick(itemPosition, itemHeight) },
                modifier = Modifier.size(24.dp)
            ) {
                androidx.compose.foundation.Image(
                    painter = painterResource(R.drawable.rider_pro_more_horizon),
                    contentDescription = null,
                    colorFilter = ColorFilter.tint(AppColors.text),
                    modifier = Modifier
                        .size(24.dp)
                )
            }
        }
            
            Spacer(modifier = Modifier.width(8.dp))

        
        // 发消息按钮 - 右对齐到与Switch相同的位置
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(14.dp))
                .background(AppColors.decentBackground)
                .clickable { onSendMessage() }
                .padding(horizontal = 12.dp, vertical = 6.dp)
        ) {
            Text(
                text = stringResource(R.string.group_members_send_message),
                style = androidx.compose.ui.text.TextStyle(
                    color = AppColors.text,
                    fontSize = 13.sp,
                    fontWeight = FontWeight.SemiBold
                )
            )
        }
    }
}


