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 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.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
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 com.aiosman.ravenow.AppStore
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.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import java.text.NumberFormat
import java.util.Locale

@Composable
fun UserItem(
    accountProfileEntity: AccountProfileEntity,
    postCount: Long = 0,
    isSelf: Boolean = false,
    onEditClick: () -> Unit = {}
) {
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current
    val followerDebouncer = rememberDebouncer()
    val followingDebouncer = rememberDebouncer()
    
    // 获取 MBTI 和星座信息
    val mbti = remember(accountProfileEntity.id) {
        AppStore.getUserMbti(accountProfileEntity.id)
    }
    val zodiac = remember(accountProfileEntity.id) {
        AppStore.getUserZodiac(accountProfileEntity.id)
    }
    
    // 格式化粉丝数
    val numberFormat = remember { NumberFormat.getNumberInstance(Locale.getDefault()) }
    val formattedFollowerCount = remember(accountProfileEntity.followerCount) {
        if (accountProfileEntity.followerCount >= 10000) {
            val wan = accountProfileEntity.followerCount / 10000.0
            if (wan >= 100) {
                "${wan.toInt()}万"
            } else {
                String.format("%.1f万", wan)
            }
        } else {
            numberFormat.format(accountProfileEntity.followerCount)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        // 顶部：头像和统计数据
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 头像
            CustomAsyncImage(
                LocalContext.current,
                accountProfileEntity.avatar,
                modifier = Modifier
                    .clip(CircleShape)
                    .size(96.dp),
                contentDescription = "",
                contentScale = ContentScale.Crop
            )
            
            // 统计数据
            Row(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(0.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                StatColumn(
                    modifier = Modifier.weight(1f),
                    value = postCount.toString(),
                    label = stringResource(R.string.posts)
                )

                StatColumn(
                    modifier = Modifier
                        .weight(1f)
                        .noRippleClickable {
                            followerDebouncer {
                                navController.navigate(
                                    NavigationRoute.FollowerList.route.replace(
                                        "{id}",
                                        accountProfileEntity.id.toString()
                                    )
                                )
                            }
                        },
                    value = formattedFollowerCount,
                    label = stringResource(R.string.followers_upper)
                )

                StatColumn(
                    modifier = Modifier
                        .weight(1f)
                        .noRippleClickable {
                            followingDebouncer {
                                navController.navigate(
                                    NavigationRoute.FollowingList.route.replace(
                                        "{id}",
                                        accountProfileEntity.id.toString()
                                    )
                                )
                            }
                        },
                    value = accountProfileEntity.followingCount.toString(),
                    label = stringResource(R.string.following_upper)
                )
            }
        }
        
        Spacer(modifier = Modifier.height(12.dp))
        
        // 中间：昵称、简介、创建者信息
        Column(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            // 昵称
            Text(
                text = accountProfileEntity.nickName,
                fontWeight = FontWeight.Bold,
                fontSize = 22.sp,
                letterSpacing = (-0.3).sp,
                color = AppColors.text
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 个人简介
            if (accountProfileEntity.bio.isNotEmpty()) {
                Text(
                    text = accountProfileEntity.bio,
                    fontSize = 13.sp,
                    color = AppColors.secondaryText,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            } else {
                Text(
                    text = "Welcome to my fantiac word i will show you something about magic",
                    fontSize = 13.sp,
                    color = AppColors.secondaryText,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            }
            
            // 创建者信息（如果是 AI 账户，可以显示创建者）
            // 注意：当前 AccountProfileEntity 没有创建者字段，这里暂时留空
            // 如果需要显示，需要从其他地方获取创建者信息
        }
        
        Spacer(modifier = Modifier.height(12.dp))
        
        // 底部：标签按钮
        Row(
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // MBTI 标签
            if (!mbti.isNullOrEmpty()) {
                ProfileTag(
                    text = mbti,
                    backgroundColor = Color(0x33FF8D28), // 255/255, 141/255, 40/255, alpha 0.2
                    textColor = AppColors.text
                )
            }
            
            // 星座标签
            if (!zodiac.isNullOrEmpty()) {
                ProfileTag(
                    text = zodiac,
                    backgroundColor = Color(0x33FFCC00), // 255/255, 204/255, 0/255, alpha 0.2
                    textColor = AppColors.text
                )
            }
            
            // 编辑标签（仅自己可见）
            if (isSelf) {
                ProfileTag(
                    text = stringResource(R.string.edit_profile),
                    backgroundColor = Color(0x14947A80), // 124/255, 116/255, 128/255, alpha 0.08
                    textColor = AppColors.text,
                    leadingIcon = {
                        EditIcon(
                            color = AppColors.text,
                            modifier = Modifier.size(16.dp)
                        )
                    },
                    onClick = onEditClick
                )
            }
        }
    }
}

@Composable
private fun StatColumn(
    modifier: Modifier = Modifier,
    value: String,
    label: String
) {
    val AppColors = LocalAppTheme.current
    Column(
        modifier = modifier
            .heightIn(min = 40.dp)
            .wrapContentWidth(Alignment.CenterHorizontally),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = value,
            fontWeight = FontWeight.Medium,
            fontSize = 15.sp,
            color = AppColors.text,
            textAlign = TextAlign.Center
        )
        Spacer(modifier = Modifier.height(2.dp))
        Text(
            text = label,
            fontWeight = FontWeight.Normal,
            fontSize = 11.sp,
            color = AppColors.text,
            textAlign = TextAlign.Center
        )
    }
}

@Composable
private fun ProfileTag(
    text: String,
    backgroundColor: Color,
    textColor: Color,
    leadingIcon: (@Composable () -> Unit)? = null,
    onClick: (() -> Unit)? = null
) {
    Box(
        modifier = Modifier
            .height(25.dp)
            .clip(RoundedCornerShape(12.dp))
            .background(backgroundColor)
            .then(
                if (onClick != null) {
                    Modifier.clickable(onClick = onClick)
                } else {
                    Modifier
                }
            )
            .padding(horizontal = 8.dp, vertical = 4.dp),
        contentAlignment = Alignment.Center
    ) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            leadingIcon?.invoke()
            Text(
                text = text,
                fontSize = 12.sp,
                color = textColor
            )
        }
    }
}

@Composable
private fun EditIcon(
    color: Color,
    modifier: Modifier = Modifier
) {
    Image(
        painter = painterResource(id = R.mipmap.bi),
        contentDescription = stringResource(R.string.edit_profile),
        modifier = modifier,
        colorFilter = ColorFilter.tint(color)
    )
}
