package com.aiosman.ravenow.ui.profile

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
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.Brush
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.platform.LocalDensity
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 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.entity.AccountProfileEntity
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.ui.NavigationRoute
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.navigateToPost
import java.text.NumberFormat
import java.util.Locale

@Composable
fun AiProfileV3(
    profile: AccountProfileEntity?,
    moments: List<MomentEntity>,
    postCount: Long? = null,
    isSelf: Boolean = false,
    onFollowClick: () -> Unit = {},
    onChatClick: () -> Unit = {},
    onShareClick: () -> Unit = {},
    onMemoryManageClick: () -> Unit = {},
    onLoadMore: () -> Unit = {},
    onComment: (MomentEntity) -> Unit = {},
) {
    val appColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val numberFormat = remember { NumberFormat.getNumberInstance(Locale.getDefault()) }
    var showMenu by remember { mutableStateOf(false) }
    
    // 判断是否是创建者
    val isCreator = remember(profile) {
        profile?.creatorProfile?.id?.let { creatorId ->
            AppState.UserId?.toLong() == creatorId
        } ?: false
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(appColors.background)
    ) {
        LazyColumn(
            modifier = Modifier.fillMaxSize()
        ) {
            // 顶部状态栏间距
            item {
                val statusBarPadding = WindowInsets.systemBars.asPaddingValues()
                Spacer(modifier = Modifier.height(statusBarPadding.calculateTopPadding()))
            }
            
            // AI大卡片
            item {
                AiProfileCard(
                    profile = profile,
                    postCount = postCount,
                    numberFormat = numberFormat
                )
            }

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

            // 三按钮交互区
            if (!isSelf) {
                item {
                    AiProfileActions(
                        profile = profile,
                        onFollowClick = onFollowClick,
                        onChatClick = onChatClick,
                        onShareClick = onShareClick
                    )
                }

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

            // 动态Grid - 使用items来渲染每个动态
            item {
                LazyVerticalGrid(
                    columns = GridCells.Fixed(3),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(((moments.size / 3 + 1) * 130).dp) // 动态计算高度
                        .padding(horizontal = 16.dp),
                    userScrollEnabled = false // 禁用内部滚动
                ) {
                    itemsIndexed(moments) { idx, moment ->
                        if (moment.images.isNotEmpty()) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .aspectRatio(1f)
                                    .padding(2.dp)
                                    .noRippleClickable {
                                        onComment(moment)
                                    }
                            ) {
                                CustomAsyncImage(
                                    imageUrl = moment.images[0].thumbnail,
                                    contentDescription = "",
                                    modifier = Modifier.fillMaxSize(),
                                    context = LocalContext.current
                                )
                            }
                        }
                    }
                }
            }

            // 底部间距
            item {
                Spacer(modifier = Modifier.height(100.dp))
            }
        }

        // 顶部返回按钮
        TopBar(
            onMenuClick = { showMenu = true }
        )
    }
    
        // 底部菜单
    if (showMenu) {
        AiProfileMenuModal(
            onDismiss = { showMenu = false },
            onChatClick = {
                showMenu = false
                onChatClick()
            },
            onShareClick = {
                showMenu = false
                onShareClick()
            },
            onEditClick = {
                showMenu = false
                // 导航到编辑页面
                profile?.chatAIId?.let { chatAIId ->
                    navController.navigate(
                        NavigationRoute.AiPromptEdit.route.replace("{chatAIId}", chatAIId)
                    )
                }
            },
            onMemoryManageClick = {
                showMenu = false
                onMemoryManageClick()
            },
            profile = profile,
            showEdit = isCreator
        )
    }
}

@Composable
private fun TopBar(
    onMenuClick: () -> Unit = {}
) {
    val navController = LocalNavController.current
    val appColors = LocalAppTheme.current

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.Transparent)
    ) {
        StatusBarSpacer()
        
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp)
                .statusBarsPadding(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 返回按钮
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(Color.Black.copy(alpha = 0.3f))
                    .noRippleClickable {
                        navController.popBackStack()
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "←",
                    fontSize = 24.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                )
            }
            
            // 菜单按钮
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(Color.Black.copy(alpha = 0.3f))
                    .noRippleClickable {
                        onMenuClick()
                    },
                contentAlignment = Alignment.Center
            ) {
                Image(
                    painter = painterResource(R.drawable.rider_pro_more_horizon),
                    contentDescription = "Menu",
                    modifier = Modifier.size(24.dp),
                    colorFilter = ColorFilter.tint(Color.White)
                )
            }
        }
    }
}

@Composable
private fun AiProfileCard(
    profile: AccountProfileEntity?,
    postCount: Long?,
    numberFormat: NumberFormat
) {
    val appColors = LocalAppTheme.current
    
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp) // 添加四边边距
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(400.dp)
                .clip(RoundedCornerShape(16.dp)) // 添加圆角
        ) {
            // 背景图 - 使用aiRoleAvatar
            val backgroundUrl = profile?.aiRoleAvatarLarge 
                ?: profile?.aiRoleAvatarMedium 
                ?: profile?.aiRoleAvatar 
                ?: profile?.avatar

            CustomAsyncImage(
                context = LocalContext.current,
                imageUrl = backgroundUrl ?: "",
                contentDescription = "AI Background",
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )

            // 底部渐变遮罩
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                Color.Transparent,
                                Color.Black.copy(alpha = 0.7f)
                            ),
                            startY = 200f,
                            endY = 1200f
                        )
                    )
            )

            // 左下角内容
            Column(
                modifier = Modifier
                    .align(Alignment.BottomStart)
                    .padding(20.dp),
                horizontalAlignment = Alignment.Start
            ) {
                // AI昵称 - 左对齐
                Text(
                    text = profile?.nickName ?: "",
                    fontSize = 22.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )

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

                // AI简介 - 左对齐
                if (!profile?.bio.isNullOrEmpty()) {
                    Text(
                        text = profile?.bio ?: "",
                        fontSize = 13.sp,
                        color = Color.White.copy(alpha = 0.85f),
                        textAlign = TextAlign.Start,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis,
                        lineHeight = 18.sp
                    )

                    Spacer(modifier = Modifier.height(12.dp))
                }

                // 统计数据行 - 左对齐
                Row(
                    horizontalArrangement = Arrangement.spacedBy(24.dp)
                ) {
                    StatItem(
                        count = postCount ?: 0L,
                        label = stringResource(R.string.posts),
                        numberFormat = numberFormat
                    )
                    StatItem(
                        count = profile?.followerCount?.toLong() ?: 0L,
                        label = stringResource(R.string.followers_upper),
                        numberFormat = numberFormat
                    )
                    StatItem(
                        count = profile?.followingCount?.toLong() ?: 0L,
                        label = stringResource(R.string.following_upper),
                        numberFormat = numberFormat
                    )
                }
            }
        }
    }
}

@Composable
private fun StatItem(
    count: Long,
    label: String,
    numberFormat: NumberFormat
) {
    Column(
        horizontalAlignment = Alignment.Start
    ) {
        Text(
            text = formatNumber(count, numberFormat),
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Spacer(modifier = Modifier.height(2.dp))
        Text(
            text = label,
            fontSize = 12.sp,
            color = Color.White.copy(alpha = 0.8f)
        )
    }
}

private fun formatNumber(count: Long, numberFormat: NumberFormat): String {
    return when {
        count >= 1_000_000 -> String.format("%.1fM", count / 1_000_000.0)
        count >= 1_000 -> String.format("%.1fK", count / 1_000.0)
        else -> numberFormat.format(count)
    }
}

@Composable
private fun AiProfileActions(
    profile: AccountProfileEntity?,
    onFollowClick: () -> Unit,
    onChatClick: () -> Unit,
    onShareClick: () -> Unit
) {
    val appColors = LocalAppTheme.current
    val navController = LocalNavController.current

    // 定义渐变色
    val followGradient = Brush.horizontalGradient(
        colors = listOf(
            Color(0xFF7c45ed),
            Color(0x777c68ef)
        )
    )

    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
    ) {
        // Follow按钮
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center,
            modifier = Modifier
                .weight(1f)
                .clip(RoundedCornerShape(8.dp))
                .let { modifier ->
                    if (profile?.isFollowing == true) {
                        // 已关注状态 - 透明背景
                        modifier.background(Color.Transparent)
                    } else {
                        // 未关注状态 - 渐变背景
                        modifier.background(brush = followGradient)
                    }
                }
                .let { modifier ->
                    if (profile?.isFollowing == true) {
                        modifier.border(
                            width = 1.dp,
                            color = appColors.text.copy(alpha = 0.3f),
                            shape = RoundedCornerShape(8.dp)
                        )
                    } else {
                        modifier
                    }
                }
                .padding(horizontal = 16.dp, vertical = 12.dp)
                .noRippleClickable {
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.FOLLOW_USER)) {
                        navController.navigate(NavigationRoute.Login.route)
                    } else {
                        onFollowClick()
                    }
                }
        ) {
            Text(
                text = if (profile?.isFollowing == true) 
                    stringResource(R.string.follow_upper_had) 
                else 
                    stringResource(R.string.follow_upper),
                fontSize = 14.sp,
                fontWeight = FontWeight.W900,
                color = if (profile?.isFollowing == true) {
                    appColors.text.copy(alpha = 0.6f)
                } else {
                    Color.White
                },
            )
        }

        // Chat按钮
        if (AppState.enableChat) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center,
                modifier = Modifier
                    .weight(1f)
                    .clip(RoundedCornerShape(8.dp))
                    .background(appColors.nonActive)
                    .padding(horizontal = 16.dp, vertical = 12.dp)
                    .noRippleClickable {
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            onChatClick()
                        }
                    }
            ) {
                Text(
                    text = stringResource(R.string.chat_upper),
                    fontSize = 14.sp,
                    fontWeight = FontWeight.W900,
                    color = appColors.text,
                )
            }
        }

        // Share按钮
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center,
            modifier = Modifier
                .weight(1f)
                .clip(RoundedCornerShape(8.dp))
                .background(appColors.nonActive)
                .padding(horizontal = 16.dp, vertical = 12.dp)
                .noRippleClickable {
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                        navController.navigate(NavigationRoute.Login.route)
                    } else {
                        onShareClick()
                    }
                }
        ) {
            Text(
                text = stringResource(R.string.share),
                fontSize = 14.sp,
                fontWeight = FontWeight.W900,
                color = appColors.text,
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AiProfileMenuModal(
    onDismiss: () -> Unit,
    onChatClick: () -> Unit,
    onShareClick: () -> Unit,
    onEditClick: () -> Unit,
    onMemoryManageClick: () -> Unit,
    showEdit: Boolean = false,
    profile: AccountProfileEntity? = null
) {
    val appColors = LocalAppTheme.current
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    
    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState,
        containerColor = appColors.background,
        dragHandle = {},
        shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(if (showEdit) 240.dp else 240.dp)
                .background(appColors.background)
                .padding(vertical = 47.dp, horizontal = 20.dp)
        ) {
            // 私信选项
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Box(
                    modifier = Modifier
                        .clip(CircleShape)
                        .noRippleClickable {
                            onChatClick()
                        }
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_message),
                        contentDescription = "",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(appColors.text)
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = stringResource(R.string.chat_upper),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    color = appColors.text
                )
            }
            
            // 分享选项
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Box(
                    modifier = Modifier
                        .clip(CircleShape)
                        .noRippleClickable {
                            onShareClick()
                        }
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_share),
                        contentDescription = "",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(appColors.text)
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = stringResource(R.string.share),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    color = appColors.text
                )
            }
            
            // 记忆管理选项
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = if (showEdit) 16.dp else 0.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Box(
                    modifier = Modifier
                        .clip(CircleShape)
                        .noRippleClickable {
                            onMemoryManageClick()
                        }
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.ic_brain_add),
                        contentDescription = "",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(appColors.text)
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = stringResource(R.string.group_chat_info_memory_manage),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    color = appColors.text
                )
            }
            
            // 编辑选项（仅创建者可见）
            if (showEdit) {
                Column(
                    modifier = Modifier
                        .weight(1f),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Box(
                        modifier = Modifier
                            .clip(CircleShape)
                            .noRippleClickable {
                                onEditClick()
                            }
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.group_info_edit),
                            contentDescription = "",
                            modifier = Modifier.size(24.dp),
                            colorFilter = ColorFilter.tint(appColors.text)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = stringResource(R.string.edit_profile),
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        color = appColors.text
                    )
                }
            }
        }
    }
}

