package com.aiosman.ravenow.ui.agent

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
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.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import com.aiosman.ravenow.LocalNavController
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.viewmodel.compose.viewModel
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.PointsPaymentDialog
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 com.aiosman.ravenow.data.PointService
import androidx.compose.runtime.collectAsState
import kotlinx.coroutines.launch

/**
 * AI Prompt 编辑页面
 */
@Composable
fun AiPromptEditScreen(
    chatAIId: String,
    viewModel: AiPromptEditViewModel = viewModel()
) {
    val context = LocalContext.current
    val navController = LocalNavController.current
    val appColors = LocalAppTheme.current
    
    // 加载Prompt详情
    LaunchedEffect(chatAIId) {
        viewModel.loadPromptDetail(chatAIId)
    }
    
    // 监听头像裁剪结果（从AgentImageCropScreen返回）
    LaunchedEffect(viewModel.isSelectingAvatar) {
        if (!viewModel.isSelectingAvatar && AddAgentViewModel.croppedBitmap != null) {
            // 从裁剪页面返回，检查是否有新的裁剪结果
            viewModel.croppedBitmap = AddAgentViewModel.croppedBitmap
            // 清空AddAgentViewModel的裁剪结果，避免影响创建页面
            AddAgentViewModel.croppedBitmap = null
        }
    }
    
    // 状态
    var showPrivacyConfirmDialog by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    val scope = rememberCoroutineScope()
    
    // 获取积分规则和余额
    val pointsRules by PointService.pointsRules.collectAsState(initial = null)
    val pointsBalance by PointService.pointsBalance.collectAsState(initial = null)
    
    // 计算是否需要付费
    val needsPayment = viewModel.needsPrivacyPayment()
    val privacyCost = viewModel.getPrivacyCost()
    val currentBalance = viewModel.getCurrentBalance()
    val balanceAfterCost = viewModel.calculateBalanceAfterCost(privacyCost)
    val isBalanceSufficient = viewModel.isBalanceSufficient(privacyCost)
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = Color(0xFFFAFAFB)),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        StatusBarSpacer()

        // 顶部导航栏
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(color = Color(0xFFFAFAFB))
                .padding(horizontal = 14.dp, vertical = 16.dp)
        ) {
            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() }
                        ) {
                            navController.navigateUp()
                        },
                    colorFilter = ColorFilter.tint(appColors.text)
                )
                Spacer(modifier = Modifier.size(12.dp))
                Text(
                    "编辑Ai",
                    fontWeight = FontWeight.W600,
                    modifier = Modifier.weight(1f),
                    fontSize = 17.sp,
                    color = appColors.text
                )
            }
        }

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

        // 内容区域
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .background(Color(0xFFFAFAFB))
        ) {
            // 头像选择
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 18.dp),
                horizontalAlignment = 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)
                                )
                            )
                        )
                        .noRippleClickable {
                            viewModel.isSelectingAvatar = true
                            // 标记为编辑模式
                            AddAgentViewModel.isSelectingAvatar = false
                            navController.navigate(NavigationRoute.AgentImageCrop.route)
                        },
                    contentAlignment = Alignment.Center
                ) {
                    when {
                        viewModel.croppedBitmap != null -> {
                            Image(
                                bitmap = viewModel.croppedBitmap!!.asImageBitmap(),
                                contentDescription = "Avatar",
                                modifier = Modifier
                                    .size(72.dp)
                                    .clip(CircleShape),
                                contentScale = ContentScale.Crop
                            )
                        }
                        viewModel.avatarUrl != null -> {
                            CustomAsyncImage(
                                context = context,
                                imageUrl = viewModel.avatarUrl!!,
                                contentDescription = "Avatar",
                                modifier = Modifier
                                    .size(72.dp)
                                    .clip(CircleShape),
                                contentScale = ContentScale.Crop
                            )
                        }
                        else -> {
                            Image(
                                painter = painterResource(id = R.mipmap.icons_infor_edit),
                                contentDescription = "Edit",
                                colorFilter = ColorFilter.tint(Color.White),
                                modifier = Modifier.size(20.dp),
                            )
                        }
                    }
                }
            }

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

            // 名称输入
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .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 = viewModel.title,
                    hint = stringResource(R.string.agent_name_hint_1),
                    background = Color.White,
                    modifier = Modifier.fillMaxWidth(),
                ) { value ->
                    viewModel.title = value
                }
            }
            
            Spacer(modifier = Modifier.height(18.dp))

            // 描述输入
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp)
            ) {
                Text(
                    text = stringResource(R.string.agent_desc),
                    fontSize = 12.sp,
                    color = appColors.text,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.height(4.dp))
                FormTextInput2(
                    value = viewModel.desc,
                    hint = stringResource(R.string.agent_desc_hint),
                    background = Color.White,
                    modifier = Modifier.fillMaxWidth(),
                ) { value ->
                    viewModel.desc = value
                }
            }

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

            // 设定权限区域
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp)
            ) {
                Text(
                    text = "设定权限",
                    fontSize = 12.sp,
                    color = appColors.text,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.height(8.dp))

                // 公开/私有切换
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(25.dp))
                        .background(Color.White)
                        .border(
                            width = 1.dp,
                            color = Color(red = 124f / 255f, green = 116f / 255f, blue = 128f / 255f, alpha = 0.08f),
                            shape = RoundedCornerShape(25.dp)
                        )
                        .padding(horizontal = 16.dp, vertical = 12.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = if (viewModel.isPublic) "公开" else "私有",
                        fontSize = 14.sp,
                        color = appColors.text,
                        fontWeight = FontWeight.W500
                    )
                    Switch(
                        checked = viewModel.isPublic,
                        onCheckedChange = { checked ->
                            if (!checked && needsPayment && !viewModel.paidForPrivacyEdit) {
                                // 需要付费，显示确认对话框
                                showPrivacyConfirmDialog = true
                            } else {
                                viewModel.isPublic = checked
                            }
                        },
                        colors = SwitchDefaults.colors(
                            checkedThumbColor = Color.White,
                            checkedTrackColor = appColors.brandColorsColor,
                            uncheckedThumbColor = Color.White,
                            uncheckedTrackColor = appColors.brandColorsColor.copy(alpha = 0.5f),
                            uncheckedBorderColor = Color.Transparent
                        ),
                        modifier = Modifier.size(width = 64.dp, height = 28.dp)
                    )
                }

                // 首次解锁AI权限提示
                if (needsPayment && !viewModel.paidForPrivacyEdit && privacyCost > 0) {
                    Spacer(modifier = Modifier.height(8.dp))
                    // 主要内容容器（去掉阴影）
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(16.dp))
                            .background(
                                color = Color(red = 251f / 255f, green = 248f / 255f, blue = 239f / 255f)
                            )
                            .border(
                                width = 1.dp,
                                color = Color(red = 243f / 255f, green = 234f / 255f, blue = 206f / 255f),
                                shape = RoundedCornerShape(16.dp)
                            )
                            .padding(12.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            // 锁图标容器
                            Box(
                                modifier = Modifier
                                    .size(32.dp)
                                    .background(
                                        color = Color(red = 1f, green = 204f / 255f, blue = 0f, alpha = 0.12f),
                                        shape = RoundedCornerShape(10.7.dp)
                                    ),
                                contentAlignment = Alignment.Center
                            ) {
                                // 锁图标（使用文本代替，实际项目中可以使用图片资源）
                                Text(
                                    text = "🔒",
                                    fontSize = 18.sp
                                )
                            }

                            Column(
                                modifier = Modifier.weight(1f)
                            ) {
                                Text(
                                    text = "首次解锁Ai权限",
                                    fontSize = 13.sp,
                                    color = Color(red = 172f / 255f, green = 127f / 255f, blue = 94f / 255f),
                                    fontWeight = FontWeight.W500
                                )
                                Spacer(modifier = Modifier.height(4.dp))
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                                ) {
                                    Text(
                                        text = "将消耗",
                                        fontSize = 12.sp,
                                        color = Color(red = 172f / 255f, green = 127f / 255f, blue = 94f / 255f)
                                    )
                                    Text(
                                        text = "$privacyCost",
                                        fontSize = 12.sp,
                                        color = Color(red = 1f, green = 141f / 255f, blue = 40f / 255f)
                                    )
                                    // 小硬币图标
                                    Box(
                                        modifier = Modifier
                                            .size(16.dp)
                                            .background(
                                                brush = Brush.linearGradient(
                                                    colors = listOf(
                                                        Color(0xFFFFD700),
                                                        Color(0xFFFFA500)
                                                    )
                                                ),
                                                shape = CircleShape
                                            )
                                    )
                                    Text(
                                        text = "解锁后可随时切换",
                                        fontSize = 12.sp,
                                        color = Color(red = 172f / 255f, green = 127f / 255f, blue = 94f / 255f)
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }

        // 底部保存按钮
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(color = Color(0xFFFAFAFB))
                .padding(horizontal = 16.dp, vertical = 16.dp)
        ) {
            ActionButton(
                text = "保存",
                enabled = !viewModel.isUpdating && !viewModel.isLoading,
                isLoading = viewModel.isUpdating,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 验证输入
                val validationError = viewModel.validate()
                if (validationError != null) {
                    errorMessage = validationError
                    return@ActionButton
                }

                // 检查是否需要付费确认
                if (needsPayment && !viewModel.paidForPrivacyEdit) {
                    showPrivacyConfirmDialog = true
                    return@ActionButton
                }

                // 执行保存
                scope.launch {
                    try {
                        viewModel.updatePrompt(context)
                        navController.navigateUp()
                    } catch (e: Exception) {
                        errorMessage = e.message ?: "保存失败"
                    }
                }
            }
        }
    }

    // 隐私权限付费确认对话框
    if (showPrivacyConfirmDialog) {
        PointsPaymentDialog(
            cost = privacyCost,
            currentBalance = currentBalance,
            balanceAfterCost = balanceAfterCost,
            isBalanceSufficient = isBalanceSufficient,
            onConfirm = {
                showPrivacyConfirmDialog = false
                scope.launch {
                    try {
                        viewModel.isPublic = false
                        viewModel.updatePrompt(context)
                        viewModel.paidForPrivacyEdit = true
                        navController.navigateUp()
                    } catch (e: Exception) {
                        errorMessage = e.message ?: "保存失败"
                    }
                }
            },
            onCancel = {
                showPrivacyConfirmDialog = false
            },
            title = "首次解锁AI权限",
            description = "将消耗 $privacyCost 派币解锁后可随时切换"
        )
    }

    // 错误提示
    errorMessage?.let { error ->
        LaunchedEffect(error) {
            kotlinx.coroutines.delay(3000)
            errorMessage = null
        }
        // TODO: 显示Toast或Snackbar
    }
}
