package com.aiosman.ravenow.ui.account

import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Edit as EditIcon
import androidx.compose.material3.Icon
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
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.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarMaskLayout
import com.aiosman.ravenow.ui.composables.debouncedClickable
import com.aiosman.ravenow.ui.composables.rememberDebouncedNavigation
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.SolidColor
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.ui.composables.pickupAndCompressLauncher
import android.widget.Toast
import java.io.File
import androidx.activity.compose.BackHandler
import com.aiosman.ravenow.ui.account.ZodiacBottomSheetHost
import com.aiosman.ravenow.ui.account.ZodiacSheetManager

/**
 * 编辑用户资料界面
 */
@Composable
fun AccountEditScreen2(onUpdateBanner: ((Uri, File, Context) -> Unit)? = null,) {
    val model = AccountEditViewModel
    val navController = LocalNavController.current
    val context = LocalContext.current
    var usernameError by remember { mutableStateOf<String?>(null) }
    var bioError by remember { mutableStateOf<String?>(null) }
    
    // 防抖导航器
    val debouncedNavigation = rememberDebouncedNavigation()

    // 添加图片选择启动器
    val scope = rememberCoroutineScope()
    val pickBannerImageLauncher = pickupAndCompressLauncher(
        context,
        scope,
        maxSize = ConstVars.BANNER_IMAGE_MAX_SIZE,
        quality = 100
    ) { uri, file ->
        // 处理选中的图片
        // 保存到 ViewModel 中，等待保存时一起上传
        model.bannerImageUrl = uri
        model.bannerFile = file
        // 如果提供了回调，也调用它（用于个人主页直接更新）
        onUpdateBanner?.invoke(uri, file, context)
    }

    fun onNicknameChange(value: String) {
        // 去除换行符，确保昵称不包含换行
        val cleanValue = value.replace("\n", "").replace("\r", "")
        model.name = cleanValue
        // 实时验证，但不显示错误（只在保存时显示）
        usernameError = when {
            cleanValue.trim().isEmpty() -> context.getString(R.string.error_nickname_empty)
            cleanValue.length < 3 -> context.getString(R.string.error_nickname_too_short)
            cleanValue.length > 20 -> context.getString(R.string.error_nickname_too_long)
            else -> null
        }
    }
    
    fun validateNickname(): String? {
        val cleanValue = model.name.replace("\n", "").replace("\r", "")
        return when {
            cleanValue.trim().isEmpty() -> context.getString(R.string.error_nickname_empty)
            cleanValue.length < 3 -> context.getString(R.string.error_nickname_too_short)
            cleanValue.length > 20 -> context.getString(R.string.error_nickname_too_long)
            else -> null
        }
    }

    val appColors = LocalAppTheme.current

    fun onBioChange(value: String) {
        // 去除换行符，确保个人简介不包含换行
        val cleanValue = value.replace("\n", "").replace("\r", "")
        model.bio = cleanValue
        // 实时验证，但不显示错误（只在保存时显示）
        bioError = when {
            cleanValue.length > 100 -> context.getString(R.string.error_bio_too_long)
            else -> null
        }
    }
    
    fun validateBio(): String? {
        val cleanValue = model.bio.replace("\n", "").replace("\r", "")
        return when {
            cleanValue.length > 100 -> context.getString(R.string.error_bio_too_long)
            else -> null
        }
    }

    fun validate(): Boolean {
        return usernameError == null && bioError == null
    }

    // 检查是否为游客模式
    if (AppStore.isGuest) {
        LaunchedEffect(Unit) {
            // 游客模式不允许编辑资料，返回上一页（防抖）
            debouncedNavigation {
                navController.navigateUp()
            }
        }
        // 游客模式时不渲染任何内容
        return
    }
    
    LaunchedEffect(Unit) {
        // 每次进入编辑页面时都重新加载当前用户的资料
        // 确保显示的是当前登录用户的信息，而不是之前用户的缓存数据
        model.reloadProfile()
    }
    
    // 处理系统返回键
    BackHandler {
        // 用户未保存直接返回，恢复所有字段到原始值
        model.resetToOriginalData()
        navController.navigateUp()
    }
    
    // 设置状态栏为透明，根据暗色模式决定图标颜色
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(Unit) {
        systemUiController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
    }
    
    StatusBarMaskLayout(
        modifier = Modifier.background(appColors.background),
        darkIcons = !AppState.darkMode, // 根据暗色模式决定图标颜色
        maskBoxBackgroundColor = Color.Transparent
    ) {
    // 挂载星座选择弹窗
    ZodiacBottomSheetHost()
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(appColors.background)
    ) {
        when {
            model.isLoading -> {
                // 加载中状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    androidx.compose.material3.CircularProgressIndicator(
                        color = appColors.main
                    )
                }
            }
            model.profile != null -> {
                Column(
                    modifier = Modifier.fillMaxSize()
                ) {
                    // 顶部背景区域（圆角在底部，覆盖状态栏）
                    // 优先显示新选择的背景图，如果没有则显示原有的背景图
                    val banner = model.bannerImageUrl?.toString() ?: model.profile?.banner
                    val statusBarPadding = WindowInsets.systemBars.asPaddingValues().calculateTopPadding()
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .offset(y = -statusBarPadding)
                    ) {
                        Box(
                            modifier = Modifier
                                .width(402.dp)
                                .height(206.dp)
                                .align(Alignment.TopCenter)
                                .clip(RoundedCornerShape(bottomStart = 32.dp, bottomEnd = 32.dp))
                        ) {
                        if (banner != null) {
                            CustomAsyncImage(
                                context = context,
                                imageUrl = banner,
                                modifier = Modifier.fillMaxSize(),
                                contentDescription = "Banner",
                                contentScale = ContentScale.Crop
                            )
                        } else {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .background(Color.Gray.copy(alpha = 0.2f))
                            )
                        }
                        
                        // 更换封面按钮（位于壁纸右下方）
                        Box(
                            modifier = Modifier
                                .align(Alignment.BottomEnd)
                                .padding(end = 16.dp, bottom = 20.dp)
                                .clip(RoundedCornerShape(12.dp))
                                .background(Color(0x5C7D7C80)) // RGB(125, 120, 128, 0.36)
                                .padding(horizontal = 8.dp, vertical = 4.dp)
                                .noRippleClickable {
                                    Intent(Intent.ACTION_PICK).apply {
                                        type = "image/*"
                                        pickBannerImageLauncher.launch(this)
                                    }
                                }
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(4.dp)
                            ) {
                                // 更换封面图标
                                Icon(
                                    painter = painterResource(id = R.mipmap.fengm),
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp),
                                    tint = Color.White
                                )
                                Text(
                                    text = stringResource(R.string.change_cover),
                                    fontSize = 12.sp,
                                    color = Color.White
                                )
                            }
                        }
                        
                        // 状态栏区域（时间、信号、电池）
                        // 这里使用系统状态栏，不单独实现
                        
                        // 导航栏区域
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp)
                        ) {
                            Spacer(modifier = Modifier.height(statusBarPadding + 12.dp))
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(bottom = 12.dp)
                            ) {
                            // 返回按钮
                            Box(
                                modifier = Modifier
                                    .size(44.dp)
                                    .clip(CircleShape)
                                    .background(Color.White.copy(alpha = 0.3f))
                                    .noRippleClickable {
                                        // 用户未保存直接返回，恢复所有字段到原始值
                                        model.resetToOriginalData()
                                        navController.navigateUp()
                                    }
                                    .align(Alignment.CenterStart),
                                contentAlignment = Alignment.Center
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.rider_pro_back_icon),
                                    contentDescription = "Back",
                                    modifier = Modifier.size(24.dp),
                                    colorFilter = ColorFilter.tint(Color.White)
                                )
                            }
                            
                            // 标题
                            Text(
                                text = stringResource(R.string.edit_profile_info),
                                fontSize = 17.sp,
                                fontWeight = FontWeight.SemiBold,
                                color = Color.White,
                                modifier = Modifier.align(Alignment.Center)
                            )
                            }
                        }
                        }
                    }
                    
                    // 用户头像区域（距离顶部-50dp，包含状态栏高度，左右居中）
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .offset(y = (-50).dp - statusBarPadding),
                        contentAlignment = Alignment.Center
                    ) {
                        val it = model.profile!!
                        Box(
                            modifier = Modifier.size(96.dp),
                            contentAlignment = Alignment.BottomEnd
                        ) {
                            // 头像
                            CustomAsyncImage(
                                context,
                                model.croppedBitmap ?: it.avatar,
                                modifier = Modifier
                                    .size(96.dp)
                                    .clip(CircleShape)
                                    .border(2.4.dp, appColors.background, CircleShape),
                                contentDescription = "",
                                contentScale = ContentScale.Crop
                            )
                            
                            // 编辑头像按钮
                            Box(
                                modifier = Modifier
                                    .size(28.dp)
                                    .clip(CircleShape)
                                    .background(Color(0xFF110C13))
                                    .border(2.dp, Color.White, CircleShape)
                                    .debouncedClickable(debounceTime = 800L) {
                                        debouncedNavigation {
                                            navController.navigate(NavigationRoute.ImageCrop.route)
                                        }
                                    },
                                contentAlignment = Alignment.Center
                            ) {
                                Icon(
                                    painter = painterResource(id = R.mipmap.bi),
                                    contentDescription = "Edit Avatar",
                                    modifier = Modifier.size(16.dp),
                                    tint = Color.White
                                )
                            }
                        }
                    }
                    

                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f)
                            .padding(horizontal = 16.dp)
                            .offset(y = (-74).dp)// 
                    ) {
                        // 昵称输入框
                        ProfileInfoCard(
                            label = stringResource(R.string.nickname),
                            value = model.name,
                            placeholder = "Value",
                            onValueChange = { onNicknameChange(it) },
                            isMultiline = false
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        // 个人简介输入框
                        ProfileInfoCard(
                            label = stringResource(R.string.personal_intro),
                            value = model.bio,
                            placeholder = "Welcome to my fantiac word i will show you something about magic",
                            onValueChange = { onBioChange(it) },
                            isMultiline = true
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        // MBTI 类型和星座
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(16.dp))
                                .background(appColors.secondaryBackground)
                        ) {
                            // MBTI 类型
                            ProfileSelectItem(
                                label = stringResource(R.string.mbti_type),
                                value = model.mbti ?: "ENFP",
                                iconColor = Color(0xFF7C45ED),
                                iconResDark = null, // TODO: 添加MBTI暗色模式图标
                                iconResLight = null, // TODO: 添加MBTI亮色模式图标
                                onClick = {
                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.MbtiSelect.route)
                                    }
                                }
                            )
                            
                            // 分隔线
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(0.3.dp)
                                    .background(appColors.divider)
                                    .padding(horizontal = 16.dp)
                            )
                            
                            // 星座（使用当前图标）
                            ProfileSelectItem(
                                label = stringResource(R.string.zodiac),
                                value = model.zodiac?.let { storedZodiac ->
                                    // 尝试找到对应的资源ID并显示当前语言的文本
                                    findZodiacResId(storedZodiac)?.let { resId ->
                                        stringResource(resId)
                                    } ?: storedZodiac // 如果找不到，显示原始存储的值
                                } ?: stringResource(R.string.zodiac_aries),
                                iconColor = Color(0xFFFFCC00),
                                iconResDark = R.mipmap.frame_4, // 星座暗色模式图标
                                iconResLight = R.mipmap.xingzuo, // 星座亮色模式图标
                                onClick = {
                                    ZodiacSheetManager.open()
                                }
                            )
                        }
                        
                        Spacer(modifier = Modifier.weight(1f))
                        
                        // 保存按钮
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(50.dp)
                                .clip(RoundedCornerShape(1000.dp))
                                .background(
                                    brush = Brush.horizontalGradient(
                                        colors = listOf(
                                            Color(0xFF7C45ED), // RGB(124, 69, 237) - 左侧
                                            Color(0xFF7C57EE), // RGB(124, 87, 238) - 中间
                                            Color(0xFF7BD8F8)  // RGB(123, 216, 248) - 右侧
                                        )
                                    )
                                )
                                .debouncedClickable(
                                    enabled = !model.isUpdating,
                                    debounceTime = 1000L
                                ) {
                                    if (model.isUpdating) return@debouncedClickable
                                    
                                    // 点击保存时重新验证
                                    val nicknameErrorMsg = validateNickname()
                                    val bioErrorMsg = validateBio()
                                    
                                    // 如果有错误，显示对应的错误提示
                                    when {
                                        nicknameErrorMsg != null -> {
                                            Toast.makeText(context, nicknameErrorMsg, Toast.LENGTH_SHORT).show()
                                            return@debouncedClickable
                                        }
                                        bioErrorMsg != null -> {
                                            Toast.makeText(context, bioErrorMsg, Toast.LENGTH_SHORT).show()
                                            return@debouncedClickable
                                        }
                                    }
                                    
                                    // 验证通过，执行保存
                                    model.viewModelScope.launch {
                                        model.isUpdating = true
                                        model.updateUserProfile(context)
                                        model.viewModelScope.launch(Dispatchers.Main) {
                                            debouncedNavigation {
                                                navController.navigateUp()
                                            }
                                            model.isUpdating = false
                                        }
                                    }
                                },
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = stringResource(R.string.save),
                                fontSize = 17.sp,
                                fontWeight = FontWeight.Normal,
                                color = Color.White
                            )
                        }
                    }
                }
            }
            else -> {
                // 没有数据且不在加载中，显示错误信息
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.error_load_profile_failed),
                        color = appColors.text
                    )
                }
            }
        }
    }
    }
}

/**
 * 信息输入卡片组件
 */
@Composable
fun ProfileInfoCard(
    label: String,
    value: String,
    placeholder: String,
    onValueChange: (String) -> Unit,
    isMultiline: Boolean = false
) {
    val appColors = LocalAppTheme.current
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(if (isMultiline) 66.dp else 56.dp) // 昵称框高度56dp，个人简介66dp
            .clip(RoundedCornerShape(16.dp))
            .background(appColors.secondaryBackground),
        contentAlignment = if (isMultiline) Alignment.TopStart else Alignment.CenterStart
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
                .padding(vertical = if (isMultiline) 11.dp else 0.dp),
            verticalAlignment = if (isMultiline) Alignment.Top else Alignment.CenterVertically
        ) {
            // 标签
            Text(
                text = label,
                fontSize = 17.sp,
                fontWeight = FontWeight.Normal,
                color = appColors.text,
                modifier = Modifier.width(100.dp)
            )
            
            Spacer(modifier = Modifier.width(16.dp))
            
            // 输入框
            Box(
                modifier = Modifier.weight(1f)
            ) {
                if (value.isEmpty()) {
                    Text(
                        text = placeholder,
                        fontSize = if (isMultiline) 15.sp else 17.sp,
                        fontWeight = FontWeight.Normal,
                        color = appColors.secondaryText,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
                
                BasicTextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = Modifier.fillMaxWidth(),
                    textStyle = androidx.compose.ui.text.TextStyle(
                        fontSize = if (isMultiline) 15.sp else 17.sp,
                        fontWeight = FontWeight.Normal,
                        color = appColors.text
                    ),
                    cursorBrush = SolidColor(appColors.text),
                    maxLines = if (isMultiline) Int.MAX_VALUE else 1,
                    singleLine = !isMultiline
                )
            }
        }
    }
}

/**
 * 选择项组件（MBTI、星座）
 */
@Composable
fun ProfileSelectItem(
    label: String,
    value: String,
    iconColor: Color,
    onClick: () -> Unit,
    iconResDark: Int? = null,
    iconResLight: Int? = null
) {
    val appColors = LocalAppTheme.current
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(56.dp)
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // 自定义图标
            Icon(
                painter = painterResource(
                    id = if (AppState.darkMode) {
                        // 暗色模式下使用和亮色模式一样的图标
                        iconResLight ?: iconResDark ?: R.mipmap.naoz
                    } else {
                        iconResLight ?: R.mipmap.naoz // 使用传入的亮色模式图标，或默认占位
                    }
                ),
                contentDescription = null,
                modifier = Modifier.size(24.dp),
                tint = iconColor
            )
            
            Text(
                text = label,
                fontSize = 17.sp,
                fontWeight = FontWeight.Normal,
                color = appColors.text
            )
        }
        
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = value,
                fontSize = 17.sp,
                fontWeight = FontWeight.Normal,
                color = appColors.secondaryText
            )
            
            Icon(
                imageVector = Icons.Default.ArrowForward,
                contentDescription = null,
                modifier = Modifier.size(8.dp),
                tint = appColors.secondaryText
            )
        }
    }
}