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.LazyColumn
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.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.*
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.snapshotFlow
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

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AddGroupMemberScreen(groupId: String, groupName: String?) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    // 状态管理
    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(searchText.text) {
        if (AddGroupMemberViewModel.errorMessage != null) {
            AddGroupMemberViewModel.clearError()
        }
    }

    // 监听selectedMembers变化，当有新成员添加时自动滚动到最后一个
    LaunchedEffect(selectedMembers.size) {
        if (selectedMembers.isNotEmpty()) {
            kotlinx.coroutines.delay(100)
            lazyRowState.animateScrollToItem(selectedMembers.size - 1)
        }
    }

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

    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(Color.Transparent)
        AddGroupMemberViewModel.groupName = groupName
        AddGroupMemberViewModel.trtcId = groupId
        AddGroupMemberViewModel.roomId = null
    }

    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.group_chat_info_add_member),
                    fontSize = 17.sp,
                    fontWeight = FontWeight.W700,
                    color = AppColors.text,
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 16.dp)
                )
            }

            // 搜索栏（暂时不实现，但保留UI）
            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()
                            }
                        }
                    )
                }
            }

            // 已选成员列表
            if (selectedMembers.isNotEmpty()) {
                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) = AddGroupMemberViewModel.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智能体列表
                        AddMemberAiAgentListScreen(
                            searchText = searchText.text,
                            selectedMemberIds = selectedMemberIds,
                            excludeRoomId = null,
                            onMemberSelect = { member ->
                                val (newSelectedMemberIds, newSelectedMembers) = AddGroupMemberViewModel.toggleMemberSelection(
                                    member, selectedMemberIds, selectedMembers
                                )
                                selectedMemberIds = newSelectedMemberIds
                                selectedMembers = newSelectedMembers
                            }
                        )
                    }
                    1 -> {
                        // 朋友列表
                        AddMemberFriendListScreen(
                            searchText = searchText.text,
                            selectedMemberIds = selectedMemberIds,
                            roomId = null,
                            onMemberSelect = { member ->
                                val (newSelectedMemberIds, newSelectedMembers) = AddGroupMemberViewModel.toggleMemberSelection(
                                    member, selectedMemberIds, selectedMembers
                                )
                                selectedMemberIds = newSelectedMemberIds
                                selectedMembers = newSelectedMembers
                            }
                        )
                    }
                }
            }

            // 确认按钮 - 固定在底部
            Button(
                onClick = {
                    if (selectedMembers.isNotEmpty()) {
                        scope.launch {
                            val success = AddGroupMemberViewModel.addMembersToGroup(selectedMembers)
                            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 = selectedMembers.isNotEmpty() && !AddGroupMemberViewModel.isLoading
            ) {
                    Text(
                        text = stringResource(R.string.lets_ride_upper),
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W600
                    )
            }

        }

        // 居中显示的错误提示弹窗
        AddGroupMemberViewModel.errorMessage?.let { error ->
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(24.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.Center),
                    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
                        )
                    }
                }
            }
        }
    }
}

// 支持excludeRoomId的AI智能体列表Screen
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AddMemberAiAgentListScreen(
    searchText: String,
    selectedMemberIds: Set<String> = emptySet(),
    excludeRoomId: Int? = null,
    onMemberSelect: (GroupMember) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val listState = rememberLazyListState()
    
    val viewModel = remember(excludeRoomId) { AddMemberAiAgentListViewModel(excludeRoomId) }
    
    val filteredAgents = viewModel.getFilteredAgents(searchText)
    
    val pullRefreshState = rememberPullRefreshState(
        refreshing = viewModel.isRefreshing,
        onRefresh = {
            viewModel.refresh(searchText)
        }
    )
    
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo }
            .collect { visibleItems ->
                if (visibleItems.isNotEmpty()) {
                    val lastVisibleItem = visibleItems.last()
                    if (lastVisibleItem.index >= filteredAgents.size - 3 && viewModel.hasMoreData && !viewModel.isLoadingMore && !viewModel.isLoading) {
                        viewModel.loadMore(searchText)
                    }
                }
            }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {
        if (viewModel.isLoading && filteredAgents.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                LottieAnimation(
                    composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                    iterations = LottieConstants.IterateForever,
                    modifier = Modifier.size(80.dp)
                )
            }
        } else {
            LazyColumn(
                state = listState,
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(
                    items = filteredAgents,
                    key = { it.id }
                ) { agent ->
                    MemberItem(
                        member = agent,
                        isSelected = selectedMemberIds.contains(agent.id),
                        onSelect = { onMemberSelect(agent) }
                    )
                }
                
                if (viewModel.isLoadingMore) {
                    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)
                            )
                        }
                    }
                }
            }
        }
        
        PullRefreshIndicator(
            refreshing = viewModel.isRefreshing,
            state = pullRefreshState,
            modifier = Modifier.align(Alignment.TopCenter),
            backgroundColor = AppColors.background,
            contentColor = AppColors.main
        )
    }
}

// 支持roomId的朋友列表Screen
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AddMemberFriendListScreen(
    searchText: String,
    selectedMemberIds: Set<String> = emptySet(),
    roomId: Int? = null,
    onMemberSelect: (GroupMember) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val listState = rememberLazyListState()
    
    val viewModel = remember(roomId) { AddMemberFriendListViewModel(roomId) }
    
    val filteredFriends = viewModel.getFilteredFriends(searchText)
    
    val pullRefreshState = rememberPullRefreshState(
        refreshing = viewModel.isRefreshing,
        onRefresh = {
            viewModel.refresh(searchText)
        }
    )
    
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo }
            .collect { visibleItems ->
                if (visibleItems.isNotEmpty()) {
                    val lastVisibleItem = visibleItems.last()
                    if (lastVisibleItem.index >= filteredFriends.size - 3 && viewModel.hasMoreData && !viewModel.isLoadingMore && !viewModel.isLoading) {
                        viewModel.loadMore(searchText)
                    }
                }
            }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {
        if (viewModel.isLoading && filteredFriends.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                LottieAnimation(
                    composition = rememberLottieComposition(LottieCompositionSpec.Asset("star_Loader.lottie")).value,
                    iterations = LottieConstants.IterateForever,
                    modifier = Modifier.size(80.dp)
                )
            }
        } else {
            LazyColumn(
                state = listState,
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(
                    items = filteredFriends,
                    key = { it.id }
                ) { friend ->
                    MemberItem(
                        member = friend,
                        isSelected = selectedMemberIds.contains(friend.id),
                        onSelect = { onMemberSelect(friend) }
                    )
                }
                
                if (viewModel.isLoadingMore) {
                    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)
                            )
                        }
                    }
                }
            }
        }
        
        PullRefreshIndicator(
            refreshing = viewModel.isRefreshing,
            state = pullRefreshState,
            modifier = Modifier.align(Alignment.TopCenter),
            backgroundColor = AppColors.background,
            contentColor = AppColors.main
        )
    }
}

