package com.aiosman.ravenow.ui.group

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
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.foundation.text.BasicTextField
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.SolidColor
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.input.TextFieldValue
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.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.TabItem
import com.aiosman.ravenow.ui.composables.TabSpacer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch

// 成员数据类
data class GroupMember(
    val id: String,
    val name: String,
    val avatar: String,
    val isAi:Boolean = false
)

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CreateGroupChatScreen() {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    // 状态管理
    var groupName by remember { mutableStateOf(TextFieldValue("")) }
    var searchText by remember { mutableStateOf(TextFieldValue("")) }
    var selectedMembers by remember { mutableStateOf(listOf<GroupMember>()) }
    var selectedMemberIds by remember { mutableStateOf<Set<String>>(emptySet()) }
    var pagerState = rememberPagerState(pageCount = { 2 })
    var scope = rememberCoroutineScope()

    // LazyRow状态管理
    val lazyRowState = rememberLazyListState()

    // 清除错误信息
    LaunchedEffect(groupName.text, searchText.text) {
        if (CreateGroupChatViewModel.errorMessage != null) {
            CreateGroupChatViewModel.clearError()
        }
    }

    // 监听页面切换，清除当前tab的选中状态（但保留已选成员列表）
    LaunchedEffect(pagerState.currentPage) {
        // 不清除selectedMemberIds，因为我们需要保持跨tab的选中状态
        // 这样用户可以在AI智能体和朋友之间切换，选中的状态会保持
    }

    // 监听selectedMembers变化，当有新成员添加时自动滚动到最后一个
    LaunchedEffect(selectedMembers.size) {
        if (selectedMembers.isNotEmpty()) {
            // 延迟一点时间确保LazyRow已经更新了布局
            kotlinx.coroutines.delay(100)
            lazyRowState.animateScrollToItem(selectedMembers.size - 1)
        }
    }

    val navigationBarPadding = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()

    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(Color.Transparent)
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
        ) {
            StatusBarSpacer()

            // 头部
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 返回按钮
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_back_icon),
                    contentDescription = "back",
                    modifier = Modifier
                        .size(24.dp)
                        .noRippleClickable {
                            navController.popBackStack()
                        },
                    colorFilter = ColorFilter.tint(AppColors.text)
                )

                // 标题
                Text(
                    text = stringResource(R.string.create_group_chat),
                    fontSize = 17.sp,
                    fontWeight = FontWeight.W700,
                    color = AppColors.text,
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 16.dp)
                )

                // 一键创建按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.noRippleClickable {
                        // 一键创建逻辑
                    }
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_new_post_add_pic),
                        contentDescription = "quick create",
                        modifier = Modifier.size(16.dp),
                        colorFilter = ColorFilter.tint(AppColors.main)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = stringResource(R.string.quick_create),
                        fontSize = 14.sp,
                        color = AppColors.main
                    )
                }
            }

            // 搜索栏
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp)
                    .background(
                        color = AppColors.inputBackground,
                        shape = RoundedCornerShape(8.dp)
                    )
                    .padding(horizontal = 16.dp, vertical = 13.dp)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_nav_search),
                        contentDescription = stringResource(R.string.search),
                        modifier = Modifier.size(16.dp),
                        colorFilter = ColorFilter.tint(AppColors.secondaryText)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    BasicTextField(
                        value = searchText,
                        onValueChange = { searchText = it },
                        textStyle = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text,
                            fontSize = 14.sp
                        ),
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                        cursorBrush = SolidColor(AppColors.text),
                        decorationBox = { innerTextField ->
                            Box {
                                if (searchText.text.isEmpty()) {
                                    Text(
                                        text = stringResource(R.string.search),
                                        color = AppColors.secondaryText,
                                        fontSize = 14.sp
                                    )
                                }
                                innerTextField()
                            }
                        }
                    )
                }
            }

            //        // 搜索栏
            //        Box(
            //            modifier = Modifier
            //                .fillMaxWidth()
            //                .padding(horizontal = 16.dp, vertical = 8.dp)
            //                .background(
            //                    color = AppColors.inputBackground,
            //                    shape = RoundedCornerShape(8.dp)
            //                )
            //                .padding(horizontal = 12.dp, vertical = 8.dp)
            //        ) {

            //                    Row(
            //                        verticalAlignment = Alignment.CenterVertically
            //                    ) {
            //                        Image(
            //                            painter = painterResource(id = R.drawable.rider_pro_nav_search),
            //                            contentDescription = stringResource(R.string.search),
            //                            modifier = Modifier.size(16.dp),
            //                            colorFilter = ColorFilter.tint(AppColors.secondaryText)
            //                        )
            //                        Spacer(modifier = Modifier.width(8.dp))
            //                        if (searchText.text.isEmpty()) {
            //                            Text(
            //                                text = stringResource(R.string.search),
            //                                color = AppColors.secondaryText,
            //                                fontSize = 14.sp
            //                            )
            //                        }
            //                        innerTextField()
            //                    }
            //                }
            //            )
            //        }

            // 群聊名称输入：同一圆角灰色矩形容器
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp)
                    .background(
                        color = AppColors.inputBackground,
                        shape = RoundedCornerShape(8.dp)
                    )
                    .padding(horizontal = 12.dp, vertical = 8.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = stringResource(R.string.group_name),
                        fontSize = 14.sp,
                        color = AppColors.text,
                        modifier = Modifier.width(80.dp)
                    )
                    BasicTextField(
                        value = groupName,
                        onValueChange = { groupName = it },
                        textStyle = androidx.compose.ui.text.TextStyle(
                            color = AppColors.text,
                            fontSize = 14.sp
                        ),
                        modifier = Modifier
                            .weight(1f),
                        singleLine = true,
                        cursorBrush = SolidColor(AppColors.text),
                        decorationBox = { innerTextField ->
                            Box(Modifier.fillMaxWidth()) {
                                if (groupName.text.isEmpty()) {
                                    Text(
                                        text = stringResource(R.string.group_name_hint),
                                        color = AppColors.inputHint,
                                        fontSize = 14.sp
                                    )
                                }
                                innerTextField()
                            }
                        }
                    )
                }
            }

            // 已选成员列表
            if (selectedMembers.isNotEmpty()) {
                // 显示选中成员数量
                /*   Text(
                       text = "已选择 ${selectedMembers.size} 个成员",
                       fontSize = 14.sp,
                       color = AppColors.secondaryText,
                       modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
                   )*/
                LazyRow(
                    state = lazyRowState,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(selectedMembers) { member ->
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            modifier = Modifier.width(48.dp)
                        ) {
                            Box {
                                CustomAsyncImage(
                                    context = context,
                                    imageUrl = member.avatar,
                                    contentDescription = member.name,
                                    defaultRes = R.drawable.default_avatar,
                                    placeholderRes = R.drawable.default_avatar,
                                    errorRes = R.drawable.default_avatar,
                                    modifier = Modifier
                                        .size(48.dp)
                                        .clip(CircleShape)
                                )

                                // 删除按钮
                                Box(
                                    modifier = Modifier
                                        .size(20.dp)
                                        .background(AppColors.error, CircleShape)
                                        .align(Alignment.TopEnd)
                                        .noRippleClickable {
                                            // 删除成员时同时更新选中状态
                                            val (newSelectedMemberIds, newSelectedMembers) = CreateGroupChatViewModel.removeSelectedMember(
                                                member, selectedMemberIds, selectedMembers
                                            )
                                            selectedMemberIds = newSelectedMemberIds
                                            selectedMembers = newSelectedMembers
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = "×",
                                        color = AppColors.mainText,
                                        fontSize = 14.sp,
                                        fontWeight = FontWeight.Bold
                                    )
                                }
                            }

                            // 名称显示
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = if (member.name.length > 5) {
                                    member.name.substring(0, 5) + "..."
                                } else {
                                    member.name
                                },
                                fontSize = 12.sp,

                                color = AppColors.text,
                                maxLines = 1,
                                modifier = Modifier.fillMaxWidth()
                                    .wrapContentWidth(Alignment.CenterHorizontally)
                            )
                        }
                    }
                }
            }

            // Tab切换
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.Bottom
            ) {
                TabItem(
                    text = stringResource(R.string.chat_ai),
                    isSelected = pagerState.currentPage == 0,
                    onClick = {
                        scope.launch {
                            pagerState.animateScrollToPage(0)
                        }
                    }
                )
                TabSpacer()
                TabItem(
                    text = stringResource(R.string.chat_friend),
                    isSelected = pagerState.currentPage == 1,
                    onClick = {
                        scope.launch {
                            pagerState.animateScrollToPage(1)
                        }
                    }
                )
            }

            // 内容区域 - 自适应填满剩余高度
            HorizontalPager(
                state = pagerState,
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f) // 这里让列表占据剩余空间
            ) {
                when (it) {
                    0 -> {
                        // AI智能体列表
                        AiAgentListScreen(
                            searchText = searchText.text,
                            selectedMemberIds = selectedMemberIds,
                            onMemberSelect = { member ->
                                val (newSelectedMemberIds, newSelectedMembers) = CreateGroupChatViewModel.toggleMemberSelection(
                                    member, selectedMemberIds, selectedMembers
                                )
                                selectedMemberIds = newSelectedMemberIds
                                selectedMembers = newSelectedMembers
                            }
                        )
                    }
                    1 -> {
                        // 朋友列表
                        FriendListScreen(
                            searchText = searchText.text,
                            selectedMemberIds = selectedMemberIds,
                            onMemberSelect = { member ->
                                val (newSelectedMemberIds, newSelectedMembers) = CreateGroupChatViewModel.toggleMemberSelection(
                                    member, selectedMemberIds, selectedMembers
                                )
                                selectedMemberIds = newSelectedMemberIds
                                selectedMembers = newSelectedMembers
                            }
                        )
                    }
                }
            }

            // 创建群聊按钮 - 固定在底部
            Button(
                onClick = {
                    // 创建群聊逻辑
                    if (selectedMembers.isNotEmpty()) {
                        scope.launch {
                            val success = CreateGroupChatViewModel.createGroupChat(
                                groupName = groupName.text,
                                selectedMembers = selectedMembers,
                                context = context
                            )
                            if (success) {
                                navController.popBackStack()
                            }
                        }
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = navigationBarPadding + 16.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = AppColors.main,
                    contentColor = AppColors.mainText,
                    disabledContainerColor = AppColors.disabledBackground,
                    disabledContentColor = AppColors.text
                ),
                shape = RoundedCornerShape(24.dp),
                enabled = groupName.text.isNotEmpty() && selectedMembers.isNotEmpty() && !CreateGroupChatViewModel.isLoading
            ) {
                if (CreateGroupChatViewModel.isLoading) {
                    Text(
                        text = "创建中...",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W600
                    )
                } else {
                    Text(
                        text = stringResource(R.string.create_group_chat),
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W600
                    )
                }
            }

        }

        // 居中显示的错误提示弹窗
        CreateGroupChatViewModel.errorMessage?.let { error ->
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(24.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.Center), // 在Box中居中对齐
                    horizontalAlignment = Alignment.CenterHorizontally, // 水平居中
                    verticalArrangement = Arrangement.Center // 垂直居中
                ) {
                    androidx.compose.material3.Card(
                        modifier = Modifier
                            .fillMaxWidth(0.8f),
                        shape = RoundedCornerShape(8.dp)
                    ) {
                        Text(
                            text = error,
                            modifier = Modifier
                                .padding(16.dp)
                                .fillMaxWidth(),
                            color = Color.Red,
                            fontSize = 14.sp,
                            textAlign = androidx.compose.ui.text.style.TextAlign.Center
                        )
                    }
                }
            }
        }
    }
}
