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 com.aiosman.ravenow.ui.modifiers.noRippleClickable
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.material3.CircularProgressIndicator
import androidx.compose.material3.Text
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.graphics.ColorFilter
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.AppState
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.ravenow.ui.network.ReloadButton
import com.aiosman.ravenow.utils.DebounceUtils
import com.aiosman.ravenow.utils.NetworkUtils

@Composable
fun UserAgentsList(
    agents: List<AgentEntity>,
    onAgentClick: (AgentEntity) -> Unit = {},
    onAvatarClick: (AgentEntity) -> Unit = {},
    hasMore: Boolean,
    isLoading: Boolean,
    showNoMoreText: Boolean = false,
    modifier: Modifier = Modifier,
    state: LazyListState,
    nestedScrollConnection: NestedScrollConnection? = null,
    showSegments: Boolean = true // 是否显示分段控制器（全部、公开、私有）
) {
    val AppColors = LocalAppTheme.current
    val listModifier = if (nestedScrollConnection != null) {
        modifier.nestedScroll(nestedScrollConnection)
    } else {
        modifier
    }

    if (agents.isEmpty()) {
        // 使用带分段控制器的空状态布局
        Box(
            modifier = listModifier.fillMaxSize()
        ) {
            AgentEmptyContentWithSegments(showSegments = showSegments)
        }
    } else {
        LazyColumn(
            state = state,
            modifier = listModifier.fillMaxSize(),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(agents) { agent ->
                UserAgentCard(
                    agent = agent,
                    onAgentClick = onAgentClick,
                    onAvatarClick = onAvatarClick
                )
            }
            
            if (isLoading) {
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 24.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = AppColors.main
                        )
                    }
                }
            } else if (!hasMore && showNoMoreText) {
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 24.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "没有更多的滋养",
                            fontSize = 14.sp,
                            color = AppColors.secondaryText
                        )
                    }
                }
            }

            item {
                Spacer(modifier = Modifier.height(80.dp))
            }
        }
    }
}

@Composable
fun UserAgentCard(
    agent: AgentEntity,
    onAgentClick: (AgentEntity) -> Unit,
    onAvatarClick: (AgentEntity) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current

    // 防抖状态
    var lastClickTime by remember { mutableStateOf(0L) }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 左侧头像
        Box(
            modifier = Modifier
                .size(48.dp)
                .background(AppColors.nonActive, RoundedCornerShape(24.dp))
                .clickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                        onAvatarClick(agent)
                    }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            if (agent.avatar.isNotEmpty()) {
                CustomAsyncImage(
                    imageUrl = agent.avatar,
                    contentDescription = "Agent头像",
                    modifier = Modifier
                        .size(48.dp)
                        .clip(RoundedCornerShape(24.dp)),
                    contentScale = ContentScale.Crop
                )
            } else {
                Image(
                    painter = painterResource(R.mipmap.rider_pro_agent),
                    contentDescription = "默认头像",
                    modifier = Modifier.size(24.dp),
                    colorFilter = ColorFilter.tint(AppColors.secondaryText)
                )
            }
        }

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

        // 中间文字内容
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(end = 8.dp)
        ) {
            // 标题
            Text(
                text = agent.title,
                fontSize = 14.sp,
                fontWeight = FontWeight.W600,
                color = AppColors.text,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )

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

            // 描述
            Text(
                text = agent.desc,
                fontSize = 12.sp,
                color = AppColors.secondaryText,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }

        // 右侧聊天按钮
        Box(
            modifier = Modifier
                .size(width = 60.dp, height = 32.dp)
                .background(
                    color = AppColors.nonActive,
                    shape = RoundedCornerShape(8.dp)
                )
                .clickable {
                    if (DebounceUtils.simpleDebounceClick(lastClickTime, 500L) {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            onAgentClick(agent)
                        }
                    }) {
                        lastClickTime = System.currentTimeMillis()
                    }
                },
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = stringResource(R.string.chat),
                fontSize = 12.sp,
                color = AppColors.text,
                fontWeight = FontWeight.W500
            )
        }
    }
}

@Composable
fun AgentEmptyContentWithSegments(
    showSegments: Boolean = true // 是否显示分段控制器（全部、公开、私有）
) {
    var selectedSegment by remember { mutableStateOf(0) } // 0: 全部, 1: 公开, 2: 私有
    val AppColors = LocalAppTheme.current
    val isNetworkAvailable = NetworkUtils.isNetworkAvailable(LocalContext.current)
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp)
    ) {
        Spacer(modifier = Modifier.height(16.dp))
        
        // 只在查看自己的智能体时显示分段控制器
        if (showSegments) {
            AgentSegmentedControl(
                selectedIndex = selectedSegment,
                onSegmentSelected = { selectedSegment = it },
                modifier = Modifier.fillMaxWidth()
            )
            
            Spacer(modifier = Modifier.height(8.dp))
        }
        
        // 空状态内容（与动态、群聊保持一致）
        Column(
            modifier = Modifier.fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            if (isNetworkAvailable) {
                Image(
                    painter = painterResource(id = R.mipmap.l_empty_img),
                    contentDescription = "暂无Agent",
                    modifier = Modifier
                        .size(width = 181.dp, height = 153.dp)
                        .align(Alignment.CenterHorizontally),
                )

                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 {
                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 = {
                        MyProfileViewModel.ResetModel()
                        MyProfileViewModel.loadProfile(pullRefresh = true)
                    }
                )
            }
        }
    }
}

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

@Composable
private fun AgentSegmentButton(
    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
fun EmptyAgentsView() {
    val AppColors = LocalAppTheme.current
    val isNetworkAvailable = NetworkUtils.isNetworkAvailable(LocalContext.current)

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 60.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        if (isNetworkAvailable) {
            Image(
                painter = painterResource(
                    id = if(AppState.darkMode) R.mipmap.ai_dark
                    else R.mipmap.ai),
                contentDescription = "暂无Agent",
                modifier = Modifier
                    .size(width = 181.dp, height = 153.dp)
                    .align(Alignment.CenterHorizontally),
            )

// 根据是否为深色模式调整间距
            Spacer(modifier = Modifier.height(if(AppState.darkMode) 9.dp else 24.dp))

            Text(
                text = "专属AI等你召唤",
                fontSize = 16.sp,
                color = AppColors.text,
                fontWeight = FontWeight.W600
            )

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

            Text(
                text = "AI将成为你的伙伴，而不是工具",
                fontSize = 14.sp,
                color = AppColors.secondaryText,
                fontWeight = FontWeight.W400
            )
        } 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 = {
                    MyProfileViewModel.ResetModel()
                    MyProfileViewModel.loadProfile(pullRefresh = true)
                }
            )
        }
    }
}
