package com.aiosman.ravenow.ui.account

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.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.Check
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
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.comment.NoticeScreenHeader
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarMaskLayout
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.form.FormTextInput
import com.aiosman.ravenow.ui.composables.debouncedClickable
import com.aiosman.ravenow.ui.composables.rememberDebouncedNavigation
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import android.util.Log

/**
 * 编辑用户资料界面
 */
@Composable
fun AccountEditScreen2() {
    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()
    fun onNicknameChange(value: String) {
        // 去除换行符，确保昵称不包含换行
        val cleanValue = value.replace("\n", "").replace("\r", "")
        model.name = cleanValue
        usernameError = when {
            cleanValue.trim().isEmpty() -> "昵称不能为空"
            cleanValue.length < 3 -> "昵称长度不能小于3"
            cleanValue.length > 20 -> "昵称长度不能大于20"
            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 -> "个人简介长度不能大于100"
            else -> null
        }
    }

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

    // 检查是否为游客模式
    if (AppStore.isGuest) {
        LaunchedEffect(Unit) {
            // 游客模式不允许编辑资料，返回上一页（防抖）
            debouncedNavigation {
                navController.navigateUp()
            }
        }
        // 游客模式时不渲染任何内容
        return
    }
    
    LaunchedEffect(Unit) {
        // 每次进入编辑页面时都重新加载当前用户的资料
        // 确保显示的是当前登录用户的信息，而不是之前用户的缓存数据
        model.reloadProfile()
    }
    StatusBarMaskLayout(
        modifier = Modifier.background(color = appColors.background).padding(horizontal = 16.dp),
        darkIcons = !AppState.darkMode,
        maskBoxBackgroundColor = appColors.background
    ) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = appColors.background),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        //StatusBarSpacer()
        Box(
            modifier = Modifier.padding(horizontal = 0.dp, vertical = 16.dp)
        ) {
            NoticeScreenHeader(
                title = stringResource(R.string.edit_profile),
                moreIcon = false
            ) {

                Icon(
                    modifier = Modifier
                        .size(24.dp)
                        .debouncedClickable(
                            enabled = validate() && !model.isUpdating,
                            debounceTime = 1000L
                        ) {
                            if (validate() && !model.isUpdating) {
                                model.viewModelScope.launch {
                                    model.isUpdating = true
                                    model.updateUserProfile(context)
                                    model.viewModelScope.launch(Dispatchers.Main) {
                                        debouncedNavigation {
                                            navController.navigateUp()
                                        }
                                        model.isUpdating = false
                                    }
                                }
                            }
                        },
                    imageVector = Icons.Default.Check,
                    contentDescription = "保存",
                    tint = if (validate() && !model.isUpdating) appColors.text else appColors.nonActiveText
                )
            }
        }
        Spacer(modifier = Modifier.height(44.dp))
        
        // 显示内容或加载状态
        Log.d("AccountEditScreen2", "UI状态 - profile: ${model.profile?.nickName}, isLoading: ${model.isLoading}")
        when {
            model.profile != null -> {
                Log.d("AccountEditScreen2", "显示用户资料内容")
                // 有数据时显示内容
                val it = model.profile!!
                Box(
                    modifier = Modifier.size(88.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CustomAsyncImage(
                        context,
                        model.croppedBitmap ?: it.avatar,
                        modifier = Modifier
                            .size(88.dp)
                            .clip(
                                RoundedCornerShape(88.dp)
                            ),
                        contentDescription = "",
                        contentScale = ContentScale.Crop
                    )
                    Box(
                        modifier = Modifier
                            .size(32.dp)
                            .clip(CircleShape)
                            .background(appColors.main)
                            .align(Alignment.BottomEnd)
                            .debouncedClickable(
                                debounceTime = 800L
                            ) {
                                debouncedNavigation {
                                    navController.navigate(NavigationRoute.ImageCrop.route)
                                }
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            Icons.Default.Add,
                            contentDescription = "Add",
                            tint = Color.White,
                        )
                    }
                }
                Spacer(modifier = Modifier.height(58.dp))
                Column(
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 16.dp)
                ) {
                    FormTextInput(
                        value = model.name,
                        label = stringResource(R.string.nickname),
                        hint = "Input nickname",
                        modifier = Modifier.fillMaxWidth(),
                        error = usernameError
                    ) { value ->
                        onNicknameChange(value)
                    }
                    FormTextInput(
                        value = model.bio,
                        label = stringResource(R.string.bio),
                        hint = "Input bio",
                        modifier = Modifier.fillMaxWidth(),
                        error = bioError
                    ) { value ->
                        onBioChange(value)
                    }
                }
            }
            model.isLoading -> {
                Log.d("AccountEditScreen2", "显示加载指示器")
                // 加载中状态
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    androidx.compose.material3.CircularProgressIndicator(
                        color = appColors.main
                    )
                }
            }
            else -> {
                Log.d("AccountEditScreen2", "显示错误信息 - 没有数据且不在加载中")
                // 没有数据且不在加载中，显示错误信息
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    androidx.compose.material3.Text(
                        text = "加载用户资料失败，请重试",
                        color = appColors.text
                    )
                }
            }
        }

    }}


}