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

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.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.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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 com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable

@Composable
fun UserAgentsRow(
    userId: Int?,
    modifier: Modifier = Modifier,
    onMoreClick: () -> Unit = {},
    onAgentClick: (AgentEntity) -> Unit = {},
    onAvatarClick: (AgentEntity) -> Unit = {},
    onAgentLongClick: (AgentEntity) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val viewModel: UserAgentsViewModel = viewModel(key = "UserAgentsViewModel_${userId ?: "self"}")
    val isSelf = userId == null
    
    // 加载用户的智能体数据
    LaunchedEffect(userId) {
        // 无论userId是否为null都加载数据
        // null表示加载当前用户自己的智能体
        viewModel.loadUserAgents(userId)
    }
    
//    // 总是显示智能体区域，即使没有数据也显示标题和状态
//    Column(
//        modifier = modifier
//            .fillMaxWidth()
//            .padding(horizontal = 16.dp)
//    ) {
//        Text(
//            text = if (isSelf) "我的智能体" else "TA的智能体",
//            fontSize = 16.sp,
//            fontWeight = FontWeight.W600,
//            color = AppColors.text,
//            modifier = Modifier.padding(bottom = 12.dp)
//        )
//
//        when {
//            viewModel.isLoading -> {
//                // 显示加载状态
//                Box(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .height(60.dp),
//                    contentAlignment = Alignment.Center
//                ) {
//                    Text(
//                        text = "加载中...",
//                        fontSize = 14.sp,
//                        color = AppColors.text.copy(alpha = 0.6f)
//                    )
//                }
//            }
//            viewModel.error != null -> {
//                // 显示错误状态
//                Box(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .height(60.dp),
//                    contentAlignment = Alignment.Center
//                ) {
//                    Text(
//                        text = "加载失败: ${viewModel.error}",
//                        fontSize = 14.sp,
//                        color = AppColors.text.copy(alpha = 0.6f)
//                    )
//                }
//            }
//            viewModel.agents.isEmpty() -> {
//                // 显示空状态
//                Box(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .height(60.dp),
//                    contentAlignment = Alignment.Center
//                ) {
//                    Text(
//                        text = if (isSelf) "您还没有创建智能体" else "TA还没有创建智能体",
//                        fontSize = 14.sp,
//                        color = AppColors.text.copy(alpha = 0.6f)
//                    )
//                }
//            }
//            else -> {
//                // 显示智能体列表
//                LazyRow(
//                    horizontalArrangement = Arrangement.spacedBy(12.dp),
//                    modifier = Modifier.fillMaxWidth()
//                ) {
//                    // 显示智能体项目
//                    items(viewModel.agents) { agent ->
//                        AgentItem(
//                            agent = agent,
//                            onClick = { onAgentClick(agent) },
//                            onAvatarClick = { onAvatarClick(agent) },
//                            onLongClick = { onAgentLongClick(agent) }
//                        )
//                    }
//
//                    // 添加"更多"按钮
//                    item {
//                        MoreAgentItem(
//                            onClick = onMoreClick
//                        )
//                    }
//                }
//            }
//        }
//
//        Spacer(modifier = Modifier.height(16.dp))
//    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun AgentItem(
    agent: AgentEntity,
    modifier: Modifier = Modifier,
    onClick: () -> Unit = {},
    onAvatarClick: () -> Unit = {},
    onLongClick: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val clickDebouncer = rememberDebouncer()
    val avatarClickDebouncer = rememberDebouncer()
    val longClickDebouncer = rememberDebouncer()

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier
            .combinedClickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = {
                    Log.d("AgentItem", "onClick triggered for agent: ${agent.title}")
                    clickDebouncer {
                        onClick()
                    }
                },
                onLongClick = {
                    Log.d("AgentItem", "onLongClick triggered for agent: ${agent.title}")
                    longClickDebouncer {
                        onLongClick()
                    }
                }
            )
    ) {
        // 头像
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .combinedClickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    onClick = {
                        Log.d("AgentItem", "Avatar clicked for agent: ${agent.title}")
                        avatarClickDebouncer {
                            onAvatarClick()
                        }
                    },
                    onLongClick = {
                        Log.d("AgentItem", "Avatar long clicked for agent: ${agent.title}")
                        longClickDebouncer {
                            onLongClick()
                        }
                    }
                )
        ) {
            CustomAsyncImage(
                context = LocalContext.current,
                imageUrl = agent.avatar,
                contentDescription = agent.title,
                modifier = Modifier.size(48.dp),
                contentScale = ContentScale.Crop,
                defaultRes = R.mipmap.rider_pro_agent
            )
        }

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

        // 名字
        Text(
            text = agent.title,
            fontSize = 12.sp,
            fontWeight = FontWeight.W500,
            color = AppColors.text,
            textAlign = TextAlign.Center,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.width(48.dp)
        )
    }
}


@Composable
private fun MoreAgentItem(
    modifier: Modifier = Modifier,
    onClick: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val debouncer = rememberDebouncer()

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier.noRippleClickable {
            debouncer {
                onClick()
            }
        }
    ) {
        // 圆形右箭头按钮
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(AppColors.background),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                painter = painterResource(id = R.drawable.rave_now_nav_right),
                contentDescription = "更多",
                tint = AppColors.text,
                modifier = Modifier.size(20.dp)
            )
        }

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

        // "更多"文字
        Text(
            text = "更多",
            fontSize = 12.sp,
            fontWeight = FontWeight.W500,
            color = AppColors.text,
            textAlign = TextAlign.Center,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.width(48.dp)
        )
    }
}

