package com.aiosman.ravenow.ui.agent

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.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.Check
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.activity.compose.BackHandler
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewModelScope
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.account.AccountEditViewModel
import com.aiosman.ravenow.ui.comment.NoticeScreenHeader
import com.aiosman.ravenow.ui.comment.ScreenHeader
import com.aiosman.ravenow.ui.comment.ScreenHeader2
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Row
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.form.FormTextInput
import com.aiosman.ravenow.ui.composables.form.FormTextInput2
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.compose.foundation.border
import androidx.compose.ui.draw.shadow
import com.aiosman.ravenow.AppState
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.StartOffset
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.offset
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.TextStyle
import com.aiosman.ravenow.ui.agent.AddAgentViewModel.showManualCreation

/**
 * 添加智能体界面
 */
@Composable
fun AddAgentScreen() {
    val model = AddAgentViewModel
    val navController = LocalNavController.current
    val context = LocalContext.current
    var agnetNameError by remember { mutableStateOf<String?>(null) }
    var agnetDescError by remember { mutableStateOf<String?>(null) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var isProcessing by remember { mutableStateOf(false) }
    var showWaveAnimation by remember { mutableStateOf(false) }
    var isCreatingAgent by remember { mutableStateOf(false) } // 控制是否处于创建状态
    var showManualCreationForm by remember { mutableStateOf(false) } // 控制是否显示手动创建表单
    var tempDesc by remember { mutableStateOf("") } // 独立的临时描述变量
    val keyboardController = LocalSoftwareKeyboardController.current

    fun onNameChange(value: String) {
        model.name = value.trim()
        agnetNameError = when {
            else -> null
        }
    }

    val appColors = LocalAppTheme.current

    fun onDescChange(value: String) {
        model.desc = value.trim()
        agnetDescError = when {
            value.length > 512 -> "简介长度不能大于512"
            else -> null
        }
    }
    fun onTempDescChange(value: String) {
        tempDesc = value.trim()
        agnetDescError = when {
            value.length > 512 -> "简介长度不能大于512"
            else -> null
        }
    }
    fun validate(): Boolean {
        return agnetNameError == null && agnetDescError == null
    }

    // AI文案优化
    suspend fun optimizeTextWithAI(content: String): String? {
        return try {
            val sessionId = ""
            val response = com.aiosman.ravenow.data.api.ApiClient.api.agentMoment(
                com.aiosman.ravenow.data.api.AgentMomentRequestBody(
                    generateText = content,
                    sessionId = sessionId
                )
            )
            response.body()?.data
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 处理系统返回键
    BackHandler {
        // 如果不是在选择头像过程中，则清空数据
        if (!model.isSelectingAvatar) {
            model.clearData()
        }
        navController.popBackStack()
    }

    // 页面进入时重置头像选择状态
    LaunchedEffect(Unit) {
        model.isSelectingAvatar = false
        // 根据标记恢复相应的状态
        if (model.isAutoModeManualForm) {
            // 恢复自动模式下的手动表单状态
            showManualCreationForm = model.showManualCreationForm
            isCreatingAgent = model.isCreatingAgent
            showWaveAnimation = model.showWaveAnimation
            showManualCreation = model.showManualCreation
        } else {
            // 恢复手动模式下的状态
            showManualCreation = model.showManualCreation
            showManualCreationForm = model.showManualCreationForm
            isCreatingAgent = model.isCreatingAgent
            showWaveAnimation = model.showWaveAnimation
        }
    }


    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = appColors.decentBackground),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        var showManualCreation by remember {
            mutableStateOf(model.showManualCreation)
        }
        StatusBarSpacer()
        Box(
            modifier = Modifier.padding(horizontal = 14.dp, vertical = 16.dp)
                .background(color = appColors.decentBackground)
        ) {
            // 自定义header，控制返回按钮行为
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Image(
                    painter = painterResource(id = R.drawable.rider_pro_back_icon),
                    contentDescription = "返回",
                    modifier = Modifier.size(24.dp).clickable(
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() }
                    ) {
                        // 与BackHandler保持一致的逻辑
                        if (!model.isSelectingAvatar) {
                            model.clearData()
                        }
                        navController.navigateUp()
                    },
                    colorFilter = ColorFilter.tint(appColors.text)
                )
                Spacer(modifier = Modifier.size(12.dp))
                Text(
                    stringResource(R.string.agent_add),
                    fontWeight = FontWeight.W600,
                    modifier = Modifier.weight(1f),
                    fontSize = 17.sp,
                    color = appColors.text
                )
            }
        }
        Spacer(modifier = Modifier.height(1.dp))

        if (!isCreatingAgent) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
                    .padding(horizontal = 20.dp),
            ) {
                Image(
                    painter = painterResource(id = R.mipmap.group_copy),
                    contentDescription = "",
                    modifier = Modifier
                        .size(48.dp)
                        .clip(
                            RoundedCornerShape(48.dp)
                        ),
                    contentScale = ContentScale.Crop
                )
            }
        }
            Spacer(modifier = Modifier.height(16.dp))
            Column(
                modifier = Modifier.fillMaxWidth()
                    .padding(start = 20.dp)
            ) {
                Text(
                    text = "${AppState.profile?.nickName ?: "User"} ${stringResource(R.string.welcome_1)}",
                    fontSize = 16.sp,
                    color = appColors.text,
                    fontWeight = FontWeight.W600
                )
            }
        if (!isCreatingAgent) {
            Spacer(modifier = Modifier.height(8.dp))
            Column(
                modifier = Modifier.fillMaxWidth()
                    .padding(start = 20.dp)
            ) {
                if (!showManualCreation) {
                    Text(
                        text = stringResource(R.string.welcome_2),
                        fontSize = 14.sp,
                        color = appColors.text.copy(alpha = 0.6f),
                    )
                }
            }
        }
            Spacer(modifier = Modifier.height(24.dp))

        if (!showManualCreation) {
            //自动创造AI界面
            Column(
                modifier = Modifier
                    .padding(horizontal = 20.dp)
            ) {

                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(95.dp)
                        .shadow(
                            elevation = 10.dp,
                            shape = RoundedCornerShape(10.dp),
                            spotColor = Color(0x33F563FF),
                            ambientColor = Color(0x99F563FF),
                            clip = false
                        )
                        .background(
                            brush = Brush.linearGradient(
                                listOf(
                                    Color(0xFF6246FF),
                                    Color(0xFF7C45ED)
                                )
                            ),
                            shape = RoundedCornerShape(10.dp)
                        )
                        .padding(0.5.dp)
                        .background(
                            color = appColors.inputBackground2,
                            shape = RoundedCornerShape(10.dp)
                        )
                ) {
                    val focusRequester = remember { FocusRequester() }

                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .noRippleClickable {
                                model.viewModelScope.launch {
                                    focusRequester.requestFocus()
                                    keyboardController?.show()
                                }
                            }
                    )

                    TextField(
                        value = tempDesc,
                        onValueChange = { value -> onTempDescChange(value) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(95.dp)
                            .focusRequester(focusRequester),
                        placeholder = {
                            Text(
                                text = stringResource(R.string.agent_desc_hint_auto),
                                color = Color.Gray
                            )
                        },
                        textStyle = TextStyle(
                            color = LocalAppTheme.current.text,
                            fontSize = 16.sp
                        ),
                        colors = TextFieldDefaults.colors(
                            focusedIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            disabledIndicatorColor = Color.Transparent,
                            focusedContainerColor = appColors.inputBackground2,
                            unfocusedContainerColor = appColors.inputBackground2,
                        ),
                        shape = RoundedCornerShape(10.dp),
                        supportingText = null,
                        trailingIcon = null,
                        leadingIcon = null
                    )

                    Row(
                        modifier = Modifier
                            .align(Alignment.BottomEnd)
                            .padding(end = 12.dp, bottom = 12.dp)
                            .noRippleClickable {
                                // 只有在有内容且未处理中且未创建中时才可点击
                                if (tempDesc.isNotEmpty() && !isProcessing && !isCreatingAgent) {
                                    isProcessing = true
                                    showWaveAnimation = true // 显示构思动画
                                    keyboardController?.hide()
                                    model.viewModelScope.launch {
                                        try {
                                            val optimizedText = optimizeTextWithAI(tempDesc)
                                            if (optimizedText != null) {
                                                onTempDescChange(optimizedText)
                                            }
                                        } catch (e: Exception) {
                                            e.printStackTrace()
                                        } finally {
                                            isProcessing = false
                                            showWaveAnimation = false
                                            isCreatingAgent = true
                                            showManualCreationForm = true
                                            onDescChange(tempDesc)
                                        }
                                    }
                                }
                            }
                            .then(
                                if (tempDesc.isEmpty() || isProcessing || isCreatingAgent) {
                                    Modifier.alpha(0.5f)
                                } else {
                                    Modifier
                                }
                            ),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(id = R.mipmap.icons_info_magic),
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                            tint = Color.Unspecified
                        )
                        Spacer(modifier = Modifier.width(5.dp))
                        Text(
                            text = stringResource(R.string.agent_text_beautify),
                            color = Color(0xFF6246FF),
                            fontSize = 14.sp
                        )
                    }
                }
            }
            Spacer(modifier = Modifier.height(24.dp))
            if ((isCreatingAgent && showWaveAnimation) || (isProcessing && showWaveAnimation)) {
                // 显示构思动画
                Row(
                    modifier = Modifier
                        .align(Alignment.Start)
                        .padding(start = 20.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier.size(18.dp)
                    ) {
                        val infiniteTransition = rememberInfiniteTransition()
                        val dot1Translation by infiniteTransition.animateFloat(
                            initialValue = 0f,
                            targetValue = -12f,
                            animationSpec = infiniteRepeatable(
                                animation = tween(
                                    durationMillis = 1000,
                                    easing = FastOutSlowInEasing
                                ),
                                repeatMode = RepeatMode.Reverse,
                                initialStartOffset = StartOffset(0)
                            )
                        )

                        val dot2Translation by infiniteTransition.animateFloat(
                            initialValue = 0f,
                            targetValue = -12f,
                            animationSpec = infiniteRepeatable(
                                animation = tween(
                                    durationMillis = 1000,
                                    easing = FastOutSlowInEasing
                                ),
                                repeatMode = RepeatMode.Reverse,
                                initialStartOffset = StartOffset(333)
                            )
                        )

                        val dot3Translation by infiniteTransition.animateFloat(
                            initialValue = 0f,
                            targetValue = -12f,
                            animationSpec = infiniteRepeatable(
                                animation = tween(
                                    durationMillis = 1000,
                                    easing = FastOutSlowInEasing
                                ),
                                repeatMode = RepeatMode.Reverse,
                                initialStartOffset = StartOffset(666)
                            )
                        )

                        // 三个彩色圆点
                        Box(
                            modifier = Modifier
                                .size(6.dp)
                                .align(Alignment.BottomStart)
                                .offset(y = dot1Translation.dp)
                                .background(Color(0xFFFFD400), CircleShape)
                        )

                        Box(
                            modifier = Modifier
                                .size(6.dp)
                                .align(Alignment.BottomCenter)
                                .offset(y = dot2Translation.dp)
                                .background(Color(0xFF2F80FF), CircleShape)
                        )

                        Box(
                            modifier = Modifier
                                .size(6.dp)
                                .align(Alignment.BottomEnd)
                                .offset(y = dot3Translation.dp)
                                .background(Color(0xFF27C84D), CircleShape)
                        )
                    }

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

                    Text(
                        text = stringResource(R.string.ideaing),
                        color = appColors.text.copy(alpha = 0.6f),
                        fontSize = 14.sp
                    )
                }
            } else if (isCreatingAgent && !showWaveAnimation && showManualCreationForm) {
                Column(
                    modifier = Modifier
                        .padding(horizontal = 16.dp)
                        .align(Alignment.Start)
                ) {
                    Text(
                        text = stringResource(R.string.avatar),
                        fontSize = 12.sp,
                        color = appColors.text,
                        fontWeight = FontWeight.W600
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Box(
                        modifier = Modifier
                            .size(72.dp)
                            .clip(CircleShape)
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(0x777c45ed),
                                        Color(0x777c68ef),
                                        Color(0x557bd8f8)
                                    )
                                )
                            )
                            .align(Alignment.Start)
                            .noRippleClickable {
                                // 保存当前状态
                                model.showManualCreationForm = showManualCreationForm
                                model.isCreatingAgent = isCreatingAgent
                                model.showWaveAnimation = showWaveAnimation
                                model.showManualCreation = showManualCreation
                                model.isAutoModeManualForm = true // 标记为自动模式下的手动表单
                                // 设置正在选择头像的标志
                                model.isSelectingAvatar = true
                                navController.navigate(NavigationRoute.AgentImageCrop.route)
                            },
                        contentAlignment = Alignment.Center
                    ){
                        // 如果已有裁剪后的头像，则显示头像，否则显示编辑图标
                        if (model.croppedBitmap != null) {
                            Image(
                                bitmap = model.croppedBitmap!!.asImageBitmap(),
                                contentDescription = "Avatar",
                                modifier = Modifier
                                    .size(72.dp)
                                    .clip(CircleShape),
                                contentScale = ContentScale.Crop
                            )
                        } else {
                            Icon(
                                painter = painterResource(id = R.mipmap.icons_infor_edit),
                                contentDescription = "Edit",
                                tint = Color.White,
                                modifier = Modifier.size(20.dp),
                            )
                        }
                    }
                    Spacer(modifier = Modifier.height(18.dp))
                    // 原版两个输入框
                    Text(
                        text = stringResource(R.string.agent_name),
                        fontSize = 12.sp,
                        color = appColors.text,
                        fontWeight = FontWeight.W600
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    FormTextInput(
                        value = model.name,
                        hint = stringResource(R.string.agent_name_hint_1),
                        background = appColors.inputBackground2,
                        modifier = Modifier.fillMaxWidth(),
                    ) { value ->
                        onNameChange(value)
                    }
                    Text(
                        text = stringResource(R.string.agent_desc),
                        fontSize = 12.sp,
                        color = appColors.text,
                        fontWeight = FontWeight.W600
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    FormTextInput2(
                        value = model.desc,
                        hint = stringResource(R.string.agent_desc_hint),
                        background = appColors.inputBackground2,
                        modifier = Modifier.fillMaxWidth(),
                    ) { value ->
                        onDescChange(value)
                    }
                }
            } else if (!isCreatingAgent && !showWaveAnimation) {
                Box(
                    modifier = Modifier
                        .align(Alignment.Start)
                        .padding(start = 20.dp)
                        .width(136.dp)
                        .height(40.dp)
                        .border(
                            width = 1.dp,
                            color = Color(0x33858B98),
                            shape = RoundedCornerShape(12.dp)
                        )
                        .background(
                            color = appColors.background,
                            shape = RoundedCornerShape(12.dp),
                        )
                        .noRippleClickable {
                            showManualCreation = true
                            tempDesc = ""
                            agnetDescError = null
                        }
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(horizontal = 18.dp, vertical = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(id = R.mipmap.icons_infor_edit),
                            contentDescription = null,
                            tint = appColors.text,
                            modifier = Modifier.size(18.dp),
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text =  stringResource(R.string.create_agent_hand),
                            color = appColors.text,
                            fontWeight = FontWeight.W600,
                            fontSize = 14.sp
                        )
                    }
                }
            }
        }else {
            //手动创造AI界面
            Column(
                modifier = Modifier
                    .padding(horizontal = 16.dp)
                    .align(Alignment.Start)
            ) {
                Box(
                    modifier = Modifier
                        .align(Alignment.Start)
                        .width(140.dp)
                        .height(40.dp)
                        .shadow(
                            elevation = 10.dp,
                            shape = RoundedCornerShape(10.dp),
                            spotColor = Color(0x33F563FF),
                            ambientColor = Color(0x99F563FF),
                            clip = false
                        )
                        .background(
                            brush = Brush.linearGradient(
                                listOf(
                                    Color(0xFF6246FF),
                                    Color(0xFF7C45ED)
                                )
                            ),
                            shape = RoundedCornerShape(10.dp)
                        )
                        .padding(0.5.dp)
                        .background(
                            color = appColors.background,
                            shape = RoundedCornerShape(10.dp),
                        )
                        .noRippleClickable {
                            showManualCreation = false
                            model.name = ""
                            model.desc = ""
                            model.croppedBitmap = null
                            isCreatingAgent = false
                            showManualCreationForm = false
                            showWaveAnimation = false
                            isProcessing = false
                        }
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(horizontal = 12.dp, vertical = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(id = R.mipmap.icons_info_magic),
                            contentDescription = null,
                            tint = appColors.text,
                            modifier = Modifier.size(18.dp),
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text =  stringResource(R.string.create_agent_auto),
                            color = appColors.text,
                            fontWeight = FontWeight.W600,
                            fontSize = 14.sp
                        )
                    }
                }

                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = stringResource(R.string.avatar),
                    fontSize = 12.sp,
                    color = appColors.text,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.height(4.dp))
                Box(
                    modifier = Modifier
                        .size(72.dp)
                        .clip(CircleShape)
                        .background(
                            brush = Brush.linearGradient(
                                colors = listOf(
                                    Color(0x777c45ed),
                                    Color(0x777c68ef),
                                    Color(0x557bd8f8)
                                )
                            )
                        )
                        .align(Alignment.Start)
                        .noRippleClickable {
                            // 保存当前状态
                            model.showManualCreation = showManualCreation
                            model.showManualCreationForm = showManualCreationForm
                            model.isCreatingAgent = isCreatingAgent
                            model.showWaveAnimation = showWaveAnimation
                            model.isAutoModeManualForm = false // 标记为手动模式下的手动表单
                            // 设置正在选择头像的标志
                            model.isSelectingAvatar = true
                            navController.navigate(NavigationRoute.AgentImageCrop.route)
                        },
                    contentAlignment = Alignment.Center
                ) {
                    // 如果已有裁剪后的头像，则显示头像，否则显示编辑图标
                    if (model.croppedBitmap != null) {
                        Image(
                            bitmap = model.croppedBitmap!!.asImageBitmap(),
                            contentDescription = "Avatar",
                            modifier = Modifier
                                .size(72.dp)
                                .clip(CircleShape),
                            contentScale = ContentScale.Crop
                        )
                    } else {
                        Icon(
                            painter = painterResource(id = R.mipmap.icons_infor_edit),
                            contentDescription = "Edit",
                            tint = Color.White,
                            modifier = Modifier.size(20.dp),
                        )
                    }
                }
            }
            Spacer(modifier = Modifier.height(18.dp))
            // 原版两个输入框
            Column(
                modifier = Modifier
                    .padding(horizontal = 16.dp)
            ) {
                Text(
                    text = stringResource(R.string.agent_name),
                    fontSize = 12.sp,
                    color = appColors.text,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.height(4.dp))
                FormTextInput(
                    value = model.name,
                    hint = stringResource(R.string.agent_name_hint_1),
                    background = appColors.inputBackground2,
                    modifier = Modifier.fillMaxWidth(),
                ) { value ->
                    onNameChange(value)
                }
                Text(
                    text = stringResource(R.string.agent_desc),
                    fontSize = 12.sp,
                    color = appColors.text,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.height(4.dp))
                FormTextInput2(
                    value = model.desc,
                    hint = stringResource(R.string.agent_desc_hint),
                    background = appColors.inputBackground2,
                    modifier = Modifier.fillMaxWidth(),
                ) { value ->
                    onDescChange(value)
                }
            }
            //手动创造AI界面
        }

        // 错误信息显示
        Spacer(modifier = Modifier.weight(1f))
        Box(modifier = Modifier.fillMaxWidth()) {
            errorMessage?.let { error ->
                Text(
                    text = error,
                    color = Color.Red,
                    modifier = Modifier
                        .padding(bottom = 20.dp)
                        .align(Alignment.Center),
                    fontSize = 14.sp
                )
            }
        }
        ActionButton(
            modifier = Modifier
                .width(345.dp)
                .padding(bottom = 40.dp)
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(
                            Color(0x777c45ed),
                            Color(0x777c68ef),
                            Color(0x557bd8f8)
                        )
                    ),
                    shape = RoundedCornerShape(24.dp)
                ),
            color = Color.White,
            backgroundColor = Color.Transparent,
            text = stringResource(R.string.create_confirm),
            isLoading = model.isUpdating,
            enabled = !model.isUpdating && validate()
        ) {
            // 验证输入
            val validationError = model.validate()
            if (validationError != null) {
                // 显示验证错误
                errorMessage = validationError
                model.viewModelScope.launch {
                    kotlinx.coroutines.delay(3000)
                    errorMessage = null
                }
                return@ActionButton
            }

            // 清除之前的错误信息
            errorMessage = null

            // 调用创建智能体API
            model.viewModelScope.launch {
                try {
                    val result = model.createAgent(context)
                    if (result != null) {
                        // 创建成功，清空数据并关闭页面
                        model.clearData()
                        navController.popBackStack()
                        AppState.agentCreatedSuccess = true
                    }
                } catch (e: Exception) {
                    // 显示错误信息
                    errorMessage = "创建智能体失败: ${e.message}"
                    e.printStackTrace()
                    // 3秒后清除错误信息
                    kotlinx.coroutines.delay(3000)
                    errorMessage = null
                }
            }
        }
    }


}
